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

The columnFilter plugin in Datatables is failing to initialize

I have a pre-existing table that needs to be customized and initialized properly. <table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table"> <thead> <tr> <th style="width: 10px;" ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

The Box element surpasses the height of the Grid component

Homepage Component <Box component="fieldset" sx={{borderRadius:2, height:"100%"}}> Application Structure Component <Grid container> <Grid item xs={4} > <Root/> </Grid> ...

Updating the content of a file on an iPhone

Is there a way to update the entire document content with a response from an ajax request? I've tested out using document.body.innerHTML and document.write(), which both work on desktop Safari. However, I'm looking for a solution that will also ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

Updates made to CSS are not reflecting on the error 404 page

Unable to Apply CSS Changes to 404 Error Page EDIT: page in question: Right from the start: I have ruled out any relative path issues. I have specified a base href in my header like this: <base href="https://hinnahackers.no/"> I am aware that thi ...

Is the stop-opacity of an SVG radialGradient not able to be animated?

I've been trying to animate the stop-opacity of a gradient within an svg element using jQuery, but for some reason, it's not working. Interestingly, when I attempt to animate stop-color with the same code, it functions properly. Here is the HTML ...

Steps for creating a table with a filter similar to the one shown in the image below

I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column format in both Business A Chaud and ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Is it possible to display a Twitter feed within a Bootstrap popover?

Is it feasible to showcase a Twitter feed within a Bootstrap popover? For instance, when the Twitter button is clicked, I aim to have my website's Twitter feed appear inside a Bootstrap popover. I have attempted the code below without success. Any a ...

How can I trigger a click event on a link using JQuery?

One of my links has the unique id: nyhedsklik There is a function associated with this link that activates when it is clicked: $('a.poplight[href^=#]').click(function() { var popID = $(this).attr('rel'); //Fetching Popup ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

Ace code editor: A guide to implementing hover error messages

Using an Ace editor, I want to enhance my website by highlighting specific code ranges and displaying error messages when they are hovered over, just like in the example image. I'm curious if this functionality can be achieved through the Ace editor ...

Mastering the correct usage of Express middleware functions in routers

Displayed in this instance, are the csrfProtection and parseForm functions being utilized as parameters/callbacks within the GET and POST requests... var cookieParser = require('cookie-parser') var csrf = require('csurf') var bodyParse ...

Is there a way to utilize the revealing prototype pattern in JavaScript to namespace functions stored within prototypes?

Currently implementing the Revealing Prototype Pattern, I have integrated two distinct prototypes within a single JavaScript file. Here are some articles that shed light on this topic: , . My assumption was that these prototypes would function like atomic ...

choosing a date from the UICalendar

Recently, I've started exploring Angular and I'm trying to incorporate a calendar feature using ui-calendar. So far, I've managed to display a basic calendar with some events on it. Now, my goal is to allow users to click on a specific day ...

Optimal arrangement for z-index and opacity

In my design, I have placed a nested link within two absolutely positioned divs structured like this: <div class="container"> <div class="leftPostHolder"> <div class="leftPost"> <h3><a href="#">link ...

Evaluating different attributes within a single entity

I was attempting to write some code that checks if two individuals share the same birthday. Person "a" and person "b" do not have the same birthday, yet the console output shows: a was born on day 1 a has the same birthday as a a has the same birthday as ...

The small screen @media query is malfunctioning and not displaying correctly

After creating an HTML file and CSS file, I have encountered a styling issue. When viewing the output on a larger screen, the text "I LOVE CODING, I WILL BECOME AN EXPERT." should be displayed in blue on a red background. However, on smaller screens, it ne ...