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

Finding the closest button using Selenium in Python

I am attempting to click on the "Delete Comment" button once I have identified a comment that contains the specific hashtag, husky, which is a clickable link. Since there are multiple "Delete Comment" buttons on the page, my approach is to locate the comm ...

Troubleshooting: Font-Face Won't Load on Any Browser

I'm completely new to using @font-face and I'm encountering some issues. Despite going through numerous posts and tutorials, I can't seem to get my fonts to load properly. I've tried activating and deactivating the font on the server, b ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

Mastering the Art of Modifying HTML with Node.js

Is it possible to manipulate HTML using Node.js? 1. First, I need to retrieve data from a database. 2. Then, I need to modify or add HTML code within Node. In essence, the goal is to fetch data and integrate it into an HTML file. The JavaScript snippet ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...

Effortless login authentication using Disqus through Google or Facebook tokens

I have set up my website to allow users to authenticate through Google and Facebook using passport, which uses the OAuth 2.0 API. Additionally, I am utilizing Disqus to manage the comments system on my site. However, I am running into a problem where user ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

What is the process for defining the host in a websocket connection?

When working on my page, I establish a websocket connection to the server using ws://127.0.0.1:5000/ws in development and ws://www.mymachine.com/ws when deployed to production. Is there a more efficient way to handle this so that I don't have to manua ...

Utilizing ellipses within a list item to create a visually appealing design

I've been struggling with this problem for hours, but I can't seem to find a solution. How can I ensure that the text in a list item respects the size of its parent container and uses an ellipsis when necessary? Here's the scenario: <?P ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

Determine the position of an element in relation to a specific ancestor using JavaScript

Let's consider the following example of HTML code: <div id="site_header_container" class="site_bar_container"> <div id="site_header"> <div id="header_logo_container"> <a class="sliced" id="header_ ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...

Error message: The Modelviewer is unable to load the local file, displaying the message "Unauthorized to access local resource."

For my WebAR project, I am utilizing Google's ModelViewer. In my vue.js project, I have a component that loads the model using the <model-viewer> attribute. My goal is to set the src attribute of the model-viewer to the absolute path of the .gl ...

Exploring the power of jQuery closures and handling events like mouseover and mouseout

I'm currently grappling with the concept of utilizing closures in conjunction with jQuery event functions. The challenge I am facing involves creating rounded shapes on the screen that stop and fade when hovered over, then resume fading when the mous ...

Check for compatibility of overflow:scroll with mobile browsers

Is there an easy JavaScript method that works across different devices and libraries? I am looking to assign a class to the html element in order to enable scrollable containers on mobile devices when needed. I want to follow a similar approach to Modern ...

Contrasting the Next 12 client-side routing with the Next 13 server-centric routing

According to the Next 13 documentation, it explains how the new router in the app directory utilizes server-centric routing to align with Server Components and data fetching on the server. Unlike the traditional pages directory that employs client-side r ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

Determining if an HTML dialog was closed using the escape key

Wondering about detecting when an HTML dialog is closed using the ESC key. Specifically referring to the HTML dialog, not jQuery. ...

The script fails to execute on content loaded through AJAX in Django

I have a website with nested div elements that make up a complete set. These elements can be dynamically loaded when the user clicks the "load more" button. The website includes a script that changes the style of the aforementioned div element when the pa ...