Modal window closed - back to the top of the page

I am struggling with a simple modal popup window that does not maintain the scroll position when closed, instead returning you to the top of the page. I am looking for a way to keep it at the same scroll position without much knowledge of Javascript.

You can find the page here:

This is the javascript code I have:

$(function(){

var appendthis =  ("<div class='modal-overlay js-modal-close'></div>");

  $('a[data-modal-id]').click(function(e) {
    e.preventDefault();
    $("body").append(appendthis);
    $(".modal-overlay").fadeTo(1000, 1);
    //$(".js-modalbox").fadeIn(500);
    var modalBox = $(this).attr('data-modal-id');
    $('#'+modalBox).fadeIn($(this).data());
  });  


$(".js-modal-close, .modal-overlay").click(function() {
  $(".modal-box, .modal-overlay").fadeOut(500, function() {
    $(".modal-overlay").remove();
  });
});

$(window).resize(function() {
  $(".modal-box").css({
    top: ($(window).height() - $(".modal-box").outerHeight()) / 2,
    left: ($(window).width() - $(".modal-box").outerWidth()) / 2
  });
});

$(window).resize();

});

Answer №1

To avoid the default behavior of the close link, you should also apply preventDefault on the open link:

$(".js-open-modal, .modal-overlay").click(function(e) {
  e.preventDefault();
  $(".modal-box, .modal-overlay").fadeOut(500, function() {
    $(".modal-overlay").remove();
  });
});

Answer №2

The reason for this issue is due to using href='#'

<a class="js-open-modal" href="#" data-modal-id="12" onclick="ga('send', 'event', 'PDF Download', 'Link Click', 'Q-Line 2.4m D Mould');"><div class="product-hover"></div></a>

To solve this problem, you can include the following JavaScript code:

$(".js-modal-close, .modal-overlay").click(function(e) {
   e.preventDefault();
   $(".modal-box, .modal-overlay").fadeOut(500, function() {
       $(".modal-overlay").remove();
   });
}

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

Unlock the ability to target and manipulate the child element of a div using jQuery

function generateImage(num) { $("<div></div>") .addClass("imageContainer") .append($("<img/>") .attr("src", images[num].url) ).appendTo("#gallery"); }//End of function GenerateImage //--- ...

Utilize Python to extract a table from an HTML document

I would like to retrieve a table from an HTML file. Below is the code-snippet I have written in order to extract the first table: import urllib2 import os import time import traceback from bs4 import BeautifulSoup #find('table',{'class&ap ...

dividing Handlebars HTML content into different files or sections

I am looking to design a single route webpage, but I would like to divide the HTML code into multiple files. When rendering this particular route, my goal is for the rendered file to pull content from different template files and combine them into one coh ...

Steps to show the chosen index value in an alert pop-up using Ionic 2 framework

I'm in the process of trying to showcase a selected index value within an Ionic 2 alert box. However, I'm struggling to find the correct method to display it in the Ionic prompt. This pertains to the home.ts import { Component } from '@ang ...

The Oracle Apex Login Interface with a Touch of Customized Styling

Currently, I'm working on creating a login page in Oracle APEX. While modifying the icon using CSS code, everything seems to be falling in place except for this one particular line: .t-Login-logo { background-image:url(#APP_FILES#LogoUpdated.jpg); bac ...

Vercel Next JS features server and client components with distinct timezones

In my Next.js 13.2.4 project, there is a useful helper function named getLocalTime(date) that retrieves the local time of the user's machine in a specific format. //Desired output: 9:30PM export function getLocalTime(date) { const localTime = new D ...

A POST request to Ajax results in a bad request error code (400)

I am looking for assistance with an ajax call that is not working as expected. I'm having trouble understanding why this is happening. Could someone please review my code and provide some insight? It appears that the call is not reaching the control ...

Transfer elements from collections employing multer

Data Payload Example:- education[0][university]: jru education[0][degree]: mca education[0][specialization]: computer application education[0][certificate_pdf_url]: (binary) education[0][degree_type]: Teaching Degree education[0][years_of_study]: [&q ...

Progressing through the Material UI LinearProgress bar in steps

How can I split a progress bar into more steps to achieve a design like this? https://i.stack.imgur.com/lRMj6.png I attempted using this code but couldn't find an option for splitting: <LinearProgress variant="determinate" classes={{ ...

Calculate the total value of an object using Typescript

Here is the data that I have: [Products, Products, Products, Products] 0: Products {product_id: "1", Product_type_id: "11", Subtotal:450, …} 1: Products {product_id: "2", Product_type_id: "22", Subtotal:550, …} 2: Products {product_id: ...

Trouble with the navigation of the JavaScript image gallery: next and previous buttons are not

Is it possible to have multiple galleries on a single page with captions? I've been trying to incorporate this JavaScript code, but struggling to make the next/previous links function for both galleries. Since I'm new to JavaScript, any advice or ...

File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint: <iron-ajax id="ajax" method="POST" url="/export/" params='' handle-as="json" on-response="handleResponse" </iron-ajax> The resp ...

Assistance with offsetting a jQuery drop down menu

This is the third jQuery script that I've been working on. While parts of it have been inspired by other scripts, I'm now focusing on implementing a specific feature. I've dedicated 4 hours to solving the issue of displaying the submenu on ...

How can I achieve auto-refresh functionality in SQLite using PHP and JavaScript without refreshing the entire page

I am currently working with a straightforward php code that retrieves data from a SQLite database by using the query "$query ="Select A from B"". The process works smoothly, and upon updating the SQLite database, I can refresh the page to display the new d ...

Testing with karma/jasmine in AngularJS can lead to issues when there are conflicts between test

Currently experiencing challenges while running my midway tests (or integration tests, which are halfway between unit tests and E2E tests). Working with an AngularJS build featuring RequireJS, I am utilizing the RequireJS plugin in Karma to run the tests. ...

jQuery function not executing after subsequent AJAX request

Can anyone provide some assistance with my AJAX/jQuery setup? I'm attempting to dynamically load code into a jQuery Dialog. There is some jQuery code within the content that initializes buttons and loads tabs. The issue I'm facing is that the c ...

Generate a list item that is contenteditable and includes a button for deletion placed beside it

I am attempting to create a ul, where each li is set as contenteditable and has a delete button positioned to the left of that li. My initial attempt looked like this: <ul id='list'> <li type='disc' id='li1' cl ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Tips for showing a single table with buttons on display

I am using R markdown and have included multiple tables with buttons, but when I open the file, all tables are displayed at once. How can I ensure only one table is shown upon opening the file? <script type="text/javascript"> function sh ...

A straightforward guide on utilizing data-attributes to achieve a linear-gradient background

considering the following input .prettyRange { -webkit-appereance: none; } .prettyRange::-webkit-slider-runnable-track { background: -webkit-linear-gradient(right, #fff 0%, green 50%, #fff 0%); } <input class="prettyRange" type="range" name="cap ...