When the click event is triggered on the modal, the page suddenly jumps to the top while applying the style of hiding the element

After implementing a modal that appears upon clicking an element on my webpage, I encountered an issue when trying to close it. I added an event listener to the 'close' link element in the top right corner of the modal with the following code snippet:

document.querySelector('.modal__close').addEventListener('click', () => {
            modal.style.display = 'none'
        })

While this successfully closes the modal, it also causes the page to abruptly scroll back to the top (I've also noticed it adds a '#' to the end of the URL). This behavior is not desired. How can I make the modal gracefully disappear without affecting the underlying display?

Answer №1

It is likely that the element in question is a hyperlink, so it is advisable to prevent its default behavior (which is to navigate to the URL specified in the href attribute).

document.querySelector('.modal__close').addEventListener('click', (ev) => {
      modal.style.display = 'none';
      ev.preventDefault();
})

Alternatively, consider using a <button> element, as it may be more suitable for this particular scenario.

Answer №2

It seems that you are facing a situation like this :

<a href="" class="modal__close"></a>

Typically, when a link (a) does not have a href attribute defined, it will reload the current page and append a # to the URL.

To prevent this default behavior, you can achieve it by using an event parameter in your Javascript:

document.querySelector('.modal__close').addEventListener('click', (ev) => {
     ev.preventDefault();
     modal.style.display = 'none';
});

In case you are using jQuery, the process is simpler:

$('.modal__close').click(function(ev){
    ev.preventDefault();
    $(modal).css('display', 'none'); // can also be $(modal).hide();
});

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

Is the renderer.setSize in Three.js calculated as a percentage of the screen size?

Is it possible to calculate the renderer.setSize based on a percentage of the screen? For instance, could I set my frame to be 80% of the device width and 80% of the device height? ...

Dropzone JavaScript returns an 'undefined' error when attempting to add an 'error event'

When using Dropzone, there is a limit of 2 files that can be uploaded at once (maxFiles: 2). If the user attempts to drag and drop a third file into the Dropzone area, an error will be triggered. myDropzone.on("maxfilesexceeded", function(file){ a ...

I am struggling to capture the user's input and display it on a webpage using HTML and JavaScript. Can you help me identify where I may be going wrong in this process?

Good day! I am fairly new to the programming world and have recently embarked on my first JavaScript project. I've chosen to create a simple budgeting app. However, I'm struggling with displaying user input on the page. Something seems off with ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

Exploring the process of implementing smooth transitions when toggling between light and dark modes using JavaScript

var container = document.querySelector(".container") var light2 = document.getElementById("light"); var dark2 = document.getElementById("dark"); light2.addEventListener('click', lightMode); function lightMode(){ contai ...

Exploring Next.js: A Guide to Implementing Browsing History in Your Application

Struggling to add entries to browser history when using Next.js's Link property for page navigation. Unable to push history entry, leading to incorrect page location in my application when going back. Any ideas on implementing this feature in Next.js? ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

Troubleshooting a deep population issue with Self-referential relationships in Mongoose

I am facing an issue with populating a self-referential model recursively multiple times. This is my schema setup: var TestSchema = new Schema({ title: { type: String }, counter: { type: Number }, children: [ { type: Schema.Types.ObjectId, ref: &apo ...

Hyphens make Tablesorter sort numeric fields uniquely

I have a table where data is displayed in the format of YYYY-####. Sometimes, there are values like 2012-456 and 2012-1234. By default, the sorting places 2012-1234 before 2012-456. If I change the sort to 'numeric', it disrupts the order of othe ...

Using Four Different Colour Borders in CSS

Is it possible to create a CSS border with 4 different colors on one side? Currently, I have the following: #header { border-color:#88a9eb; } I aim to achieve a border featuring four solid colors split equally at 25% each. Can this be done? I am looking ...

Ways to overlook concealed elements within a Bootstrap Button Group

Within my button group, there are 10 buttons. On certain screen widths, using media queries for responsiveness, I hide some buttons. The issue arises when the last button is hidden - the rounded edges of the succeeding visible button are not maintained. ...

Combining arrays to append to an array already in place

I have implemented the rss2json service to fetch an rss feed without pagination support. Instead of a page parameter, I can utilize the count parameter in my request. With this setup, I am successfully able to retrieve and display the feed using a service ...

Bring in LOCAL .obj for loading with Three.js OBJLoader in a React environment

Attempting to import a local .obj file using the THREE.OBJLoader().load() function is causing issues. While it successfully loads non-local URLs such as '', loading the local file takes a long time due to downloading it every time. The setup inv ...

Ways to rearrange targeted td elements within a table

My current table structure looks like the one shown in this https://i.sstatic.net/NCFH4.png image, but I need to change it to match the structure in this https://i.sstatic.net/7FYXI.png image. I've been searching on SO and other platforms for a solut ...

Encountering an issue of receiving "Undefined" while attempting to access constant data from a ReactJS file within my NodeJS

I am currently working on a file named check-rates that stores useStates() which are inputs provided by users. These inputs are essential for me to calculate and provide an estimated value for their shipment using the DHL API. In my nodejs express server, ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

acquire data from a JSON array

Attempting to extract the SKU from a URL www.mbsmfg.co/shop/coles-grey/?format=json-pretty in JSON format, and display available values under variants for that specific product to users. For example, when a user visits www.mbsmfg.co/shop/coles-grey/, th ...

Tips on accessing a function or variable within a script executed using $.getScript

After running a script with $.getScript, is there a way to access the namespace of that script? I expected to be able to do so since the plugin function is defined in the global scope. index.js $.getScript('plugin.js').then((...result) => co ...

Universal CSS styling for scrollbar design across platforms

I'm feeling extremely frustrated right now because I can't seem to create a basic scroll bar with a specific color and thickness that will display properly on various web browsers and smartphones. Are there any resources available to help me fig ...

Validating the existence of a URL using jQuery and AJAX

I'm currently facing a puzzling situation. I'm attempting to iterate through a list of Youtube ids to verify if the videos still exist. I've stored all the ids in an array and I'm utilizing the gdata API to determine if I receive XML r ...