Preventing Javascript Pop Up from automatically jumping to the top of the page

Upon clicking a button (refer to image below and take note of the scroll bar position), a div pop up is triggered through Javascript.

View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview

However, when the button is clicked, the pop-up appears at the very TOP of the page.

View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRWjFPS0xEV0tTeFk/preview

I am seeking assistance to make the pop-up appear centered exactly where the page is scrolled when the button is clicked.

Below is the code. Any help would be greatly appreciated! Thank you!

Javascript:

$(document).ready(function(){
//open popup
$("#pop").click(function(){
  $("#overlay_form").fadeIn(1000);
  positionPopup();
});

//close popup
$("#close").click(function(){
    $("#overlay_form").fadeOut(500);
});
});

//position the popup at the center of the page
function positionPopup(){
  if(!$("#overlay_form").is(':visible')){
    return;
  } 
  $("#overlay_form").css({
      left: ($(window).width() - $('#overlay_form').width()) / 2,
      top: ($(window).width() - $('#overlay_form').width()) / 7,
      position:'absolute'
  });
}

//maintain the popup at center of the page when browser resized
$(window).bind('resize',positionPopup);

HTML:

<a href="#" id="pop" ><li style="float:right; margin-left:5px; list-style-type:none; line-height:0px; padding-top:20px;"><i class="fa fa-share-square fa-lg"></i></li></a>
              <br />
<form id="overlay_form" style="display:none">
        <a href="#" id="close" >Close</a>

    <h2> Hello, World.</h2>
    Share buttons here :-)
</form>

Answer №1

Have you considered positioning the popup using CSS rather than JS?

You can achieve the desired effect by setting the modal as follows:

#overlay_form {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -00px;  /* Adjust based on modal height */
  margin-left: -00px; /* Adjust based on modal width */
}

This method eliminates the need for JavaScript to handle resizing events. The modal can still be shown or hidden using your current method.

P.S. Don't forget to specify a width and height for your modal element for the above technique to function correctly.

EDIT: Consider enclosing the form within a wrapper div and making that wrapper the popup container instead of the form itself. Here's an example:

HTML

<div class="pop-up">
    <form id="overlay_form">
        <a href="#" id="close">Close</a>
        <h2>Hello, World.</h2>
        Share buttons here :-)
    </form>
</div>

CSS

.pop-up {
  position: fixed;
  width: 300px;   /* Customize according to your needs */
  height: 150px;  /* Customize according to your needs */
  top: 50%;
  left: 50%;
  margin-top: -75px;  /* 1/2 of the height (150 / 2) */
  margin-left: -150px; /* 1/2 of the width (300 / 2) */
}

JSFiddle Example

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

Issue with Dynamic Theming in Ionic Framework

Currently, I am using Ionic in combination with Angular to create an App. I have introduced dynamic theming by adding two .scss files into my theme folder. In my app.scss file, I define the layout of components without colors, while all color styles are st ...

Unlocking JSON data with identical keys using JavaScriptLearn how to access JSON data with

I need help converting my JSON training data that includes classes and sentences into a different format. [ { class: 'Reservation', sentence: 'make reservation' }, { class: 'Reservation', sentence: 'do reservation&a ...

What is the best way to center a div horizontally when the width is unknown?

Check out the full screen result here: http://jsfiddle.net/anik786/UYkSf/4/embedded/result/ Here's where you can find the HTML/CSS: http://jsfiddle.net/anik786/UYkSf/4/ This is the HTML code: <div class="gallery_container"> <div class="pic ...

Is there a way to make text fade in and out smoothly instead of abruptly disappearing and reappearing after an animation ends?

I'm seeking a unique animation effect for my right-to-left scrolling text. Instead of the text teleporting back to its origin at the end of the animation, I would like it to smoothly disappear and reappear from the margins. .custom-animation { he ...

There is excessive white space at the bottom of my Index page after the footer that needs to be removed

Recently began working on converting a PSD to HTML and I've reached a point where everything seems fine. However, I understand that my CSS programming may not be the best at the moment. With your help, I am confident that I can learn and improve gradu ...

Pattern matching excluding "two or more" white spaces

Looking for a unique regular expression that meets the following criteria: No spaces allowed at the beginning or end of a line Only one space permitted between words The previous attempt using "^[АЯ-Ёа-яё0-9' ']+$" didn't q ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

Combining two objects in AngularJS to create a new merged object

Is there a way to merge object1 and object2 into object3, updating values corresponding to matching keys while ignoring unmatching keys? var object1 = { "pii" : "val1", "loc" : "val2" } var object2 = { "rrb" : "val3", "voc" : "val4" } var obje ...

Navigate quickly to different sections using jump links and adjust the positioning with the style attribute, such as "padding-top

My website incorporates Jump Links to navigate between page elements as part of an interactive User Guide. Everything functions properly on Firefox, IE, and Edge, but Chrome and Opera seem to disregard the 'padding'. Due to a fixed menu bar on t ...

Personalizing the look of Stripe Payment Component in a React Application

Currently, I have integrated the Stripe Payment Element into my React application using the code snippet below: import { useStripe, useElements, PaymentElement, } from '@stripe/react-stripe-js' export const PaymentDetails = () => { const st ...

Show SVG in img tag on entire screen

I am facing an issue where my SVG image is not fully visible when displayed within an img tag on the browser's full screen. The bottom part of the image gets truncated, making it inaccessible to users. Below is the code snippet I have been using: ht ...

Establishing the Default Volume within a script

I'm looking to adjust the default volume of music on my website. Currently, it plays too loudly on load, but I have a slider bar that allows users to change the volume. How can I set the default volume to be 25% of the slider? CHECK OUT MY WEBSITE! ...

AFRAME - Enhanced scene overlay

I am currently exploring ways to implement an overlay menu on top of an A-FRAME scene. A great example of what I am aiming for can be found on this website -> By clicking on one of the tiles in the home menu, you will see that the previous scene is mo ...

Implementing Jquery to Identify the Matching Indices of Two Arrays

I need to find the indices of similar values in array1 and array2, and then save them in a variable named stored_index. array1 = ["50","51","52","53","54","55","56","57","58","59"]; array2 = ["59","55","51"]; The desired result for stored_index is: sto ...

Send both queries using JSON

I am trying to pass company information using Json, and I also want to pass the areas using the same method. However, I am encountering some issues. Can anyone provide assistance? if($_GET['method']=="get_all_companies"){ $query = "SELECT co ...

Save the LINQ query output as a JSON object and transfer it to JavaScript

I have a question regarding handling queries in ASP.NET 3.5 and converting them into JSON objects for use in JavaScript. Here's what I've done so far, but I'm not sure if it's the correct approach: List<NCDCPoint> dupli = (fr ...

Error on JSP Hello Page

As a novice in JSP, I am attempting to create a simple JSP page where I can set my class fields for name and surname and display them on the page. Below is my Java class: package org.mypackage.person; /** * * @author cemalinanc */ public class Person ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

Blazor JavaScript interop encountering difficulty sending parameters to C# function

I'm encountering an issue where I cannot pass arguments to a C# method from JS in Blazor. Here is the code snippet causing the problem: <button class="m-2 btn btn-secondary" @onclick="FindMultiplication">Show Sum</button& ...