Tips for aligning the dialog box in the center of the screen based on the current scroll position

Is there a way to center the dialog box vertically at the current scroll position of the window when any of the "show dialog" buttons are clicked?

For instance, if I click on location 3, I want the dialog box to be centered vertically within the current viewing window. This behavior should apply to all buttons.

$('.show-dialog-btn').click(function() {

  $('#dialog-box').addClass('display-dialog-box');
});
    


$('.close-dialog-btn').click(function() {

  $('#dialog-box').removeClass('display-dialog-box');
});
.locations-container {
  padding: 10px
}

.locations-container:not(last-of-type) {
  margin-bottom: 100px
}

.locations-container:nth-child(3) {
  background: #eee
}

#dialog-box {
  top: 50%;
  left: 50%;
  z-index: 99;
  display: none;
  width: 220px;
  color: #4a4a4a;
  position: absolute;
  border-radius: 10px;
  background: #fff;
  padding: 10px;
  transform: translate(-50%, -50%);
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 1px 5px 4px rgba(0, 0, 0, 0.1)
}

#dialog-box.display-dialog-box {
  display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!--- Locations 1 Div ---->
<div class="locations-container">
  <h2>Locations 1</h2>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Delectus aliquid quas, ut fugiat, ipsum, veniam aut fuga impedit sunt laboriosam praesentium ullam quisquam eos rem voluptas corporis vel hic natus!</p>

  <button class="show-dialog-btn">Show Dialog</button>
</div>


<!--- Locations 2 Div ---->
<div class="locations-container">
  <h2>Locations 2</h2>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Delectus aliquid quas, ut fugiat, ipsum, veniam aut fuga impedit sunt laboriosam praesentium ullam quisquam eos rem voluptas corporis vel hic natus!</p>

  <button class="show-dialog-btn">Show Dialog</button>
</div>


<!--- Locations 3 Div ---->
<div class="locations-container">
  <h2>Locations 3</h2>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Delectus aliquid quas, ut fugiat, ipsum, veniam aut fuga impedit sunt laboriosam praesentium ullam quisquam eos rem voluptas corporis vel hic natus!</p>

  <button class="show-dialog-btn">Show Dialog</button>
</div>


<!--- Dialog Box ---->
<div id="dialog-box">

  <h1>Dialog box</h1>
  <p>Dialog text</p>
  <button class="close-dialog-btn">Close box </button>
</div>

Answer №1

Simply update position: absolute to fixed in the CSS code for #dialog-box:

$('.show-dialog-btn').click(function() {

  $('#dialog-box').addClass('display-dialog-box');
  $('body').addClass('disable-scroll');
});
  
$('.close-dialog-btn').click(function() {

  $('#dialog-box').removeClass('display-dialog-box');
  $('body').removeClass('disable-scroll');
});
.locations-container {
  padding: 10px
}

.locations-container:not(last-of-type) {
  margin-bottom: 100px
}

.locations-container:nth-child(3) {
  background: #eee
}

#dialog-box {
  top: 50%;
  left: 50%;
  z-index: 99;
  display: none;
  width: 220px;
  color: #4a4a4a;
  position: fixed; /* Change this line */
  border-radius: 10px;
  background: #fff;
  padding: 10px;
  transform: translate(-50%, -50%);
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 1px 5px 4px rgba(0, 0, 0, 0.1)
}

#dialog-box.display-dialog-box {
  display: block
}

body.disable-scroll {
  overflow: hidden !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!--- Locations 1 Div ---->
<div class="locations-container">
  <h2>Locations 1</h2>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Delectus aliquid quas, ut fugiat, ipsum, veniam aut fuga impedit sunt laboriosam praesentium ullam quisquam eos rem voluptas corporis vel hic natus!</p>

  <button class="show-dialog-btn">Show Dialog</button>
</div>


<!--- Locations 2 Div ---->
<div class="locations-container">
  <h2>Locations 2</h2>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Delectus aliquid quas, ut fugiat, ipsum, veniam aut fuga impedit sunt laboriosam praesentium ullam quisquam eos rem voluptas corporis vel hic natus!</p>

  <button class="show-dialog-btn">Show Dialog</button>
</div>


<!--- Locations 3 Div ---->
<div class="locations-container">
  <h2>Locations 3</h2>
  <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Delectus aliquid quas, ut fugiat, ipsum, veniam aut fuga impedit sunt laboriosam praesentium ullam quisquam eos rem voluptas corporis vel hic natus!</p>

  <button class="show-dialog-btn">Show Dialog</button>
</div>


<!--- Dialog Box ---->
<div id="dialog-box">

  <h1>Dialog box</h1>
  <p>Dialog box text</p>
  <button class="close-dialog-btn">Close box </button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...

Issue with sending files to web API using Angular FormData

After stepping through the code, I noticed that my formData is empty when it reaches the API side, with the parameter pFileToUpload having a value of null. Step 1: HTML <div class="form-group"> <input type="file" id="f ...

AngularJS: default option not being selected in dropdown menus

I need assistance with a dropdown list issue. See the code snippet below: My Controller (function(angular) { 'use strict'; angular.module('ngrepeatSelect', []) .controller('ExampleController', ['$scope', functi ...

Organizing a mat-table by date does not properly arrange the rows

My API retrieves a list of records for me. I would like to display these records sorted by date, with the latest record appearing at the top. However, the TypeScript code I have written does not seem to be ordering my rows correctly. Can anyone assist me ...

Latest news on KnockoutJS enhancements

Is there a way to create an HTML markup with a GIF progress bar that appears when the page is loading? I want to use Ajax to fetch data, populate the markup, and then hide the GIF. How can I achieve this functionality using KnockoutJS? var Item = functi ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

Tips for running Scrapy and Selenium on a webpage that utilizes angular JavaScript to serve data

I have been working on a web scraper that follows this process: Visit site A -> click on the buy now button -> redirected to Amazon -> scrape data -> return to site A The issue I am facing is that the site is built using AngularJS, and I am h ...

Exploring the compatibility of Angular.js with iframes in Firefox

For some reason, I can't seem to get iframes to work properly in Firefox when using Angular.js routes. It's probably something simple that I'm missing, but I just can't figure it out. If you want to take a look at the code, here is a ...

Executing a .sh script upon loading a webpage

Is there a way to automatically run a .sh file on webpage load to fetch a JSON file using cURL, without making it visible? I need to keep the API key confidential. ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

Adjust the class of a div element located close to its ancestor using JavaScript

I'm trying to change the class of the element #sidePanel from .compact to .expanded dynamically in this code snippet: <div id="sidePanel" class="compact"></div> <div id="topbar"> <div id="buttonContainer"> <div ...

Enhancing Vue Filtered Lists for Increased Dynamism

Currently, I am iterating through a list of items using the v-for directive. Before displaying the list, I apply a filter based on a specific value using the .filter() method. To switch between different filtered values, I utilize the v-on:click event. How ...

A guide to sorting an array based on user input using Javascript

I have developed an app that utilizes JavaScript and the VueJS framework. I am currently working on implementing a 'dropdown' feature for items that are dynamically filtered based on user input. Below is the code snippet responsible for renderin ...

The removeClass method does not affect the class attribute when using $(this).attr('class'), but only when using $(this).attr('id')

I am currently facing an issue with reducing the size of my jQuery code. The main function is to validate a form - if empty, I want to add a class of 'highlight' or remove it using addClass('highlight') and removeClass('highlight&a ...

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

Responsive column display on mobile devices can be optimized by configuring columns to appear in a 2x3 or 1x6 layout. This can be achieved even with

Currently utilizing the Avada Fusion Theme, my ability to edit core theme HTML files is limited. Fortunately, I do have access to Custom CSS. The challenge I am facing involves adjusting the display of the columns to appear as 2x3 instead of 1x6 on mobil ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

Difficulty arises when attempting to pass a PHP variable as an argument within a MySQL query

My current task involves using a PHP variable as a search term in querying a MySQL database. First, I retrieve the variables from an HTML form: <?php //Set up variables $vals = array($_POST["id_number"], $_POST["id_name"], $_POST["id_submitname"]); $ke ...