What steps can I take to resolve the issue of my popup closing automatically upon opening and simultaneously refreshing my webpage?

After creating a popup in my HTML page, when I click on the element that triggers it, the popup appears for a brief moment before automatically closing and causing my page to refresh.

Below is the code I am using:

HTML Code :

<a class="lv-footer" id="openPop" href="">Visualiser plus de détails</a>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<p>Some text in the Modal..</p>
</div>

CSS code :

.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}

.modal-content {
background-color: #fefefe;
margin: auto;
 padding: 20px;
border: 1px solid #888;
width: 80%;
}

.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}

and JS code:

var modal = document.getElementById('myModal');
var btn = document.getElementById("openPop");
var span = document.getElementsByClassName("close")[0];

 btn.onclick = function() {
modal.style.display = "block";
 }

span.onclick = function() {
modal.style.display = "none";
}

window.onclick = function(event) {
if (event.target == modal) {
    modal.style.display = "none";
}
}

I'm experiencing difficulty with this setup. Can you help me identify the issue?

Answer №1

var modal = document.getElementById('myModal');

// Retrieve the button that triggers the modal
var btn = document.getElementById("openPop");

// Get the <span> element used to close the modal
var span = document.getElementsByClassName("close")[0];

// Open the modal when the user clicks the button
btn.onclick = function(event) {
    event.preventDefault();
    modal.style.display = "block";
}

// Close the modal when the user clicks on the <span> (x)
span.onclick = function() {
    modal.style.display = "none";
}

// Close the modal when the user clicks outside of it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
.modal {
    display: none; /* Initially hidden */
    position: fixed; /* Fixed positioning */
    z-index: 1; /* Top layer */
    padding-top: 100px; /* Positioning */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scrolling */
    background-color: rgb(0,0,0); /* Fall back color */
    background-color: rgba(0,0,0,0.4); /* Black with opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
<a class="lv-footer" id="openPop" href="">See more details</a>
                <div id="myModal" class="modal">

                    <!-- Modal content -->
                    <div class="modal-content">
                        <span class="close">&times;</span>
                        <p>Some text in the Modal..</p>
                    </div>

Include event.preventDefault() when button is clicked, as it's an anchor tag. This prevents the default behavior of the anchor tag which redirects.

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

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

applying a margin to the cover div

I am currently working on a #cover element with the following CSS styling: #cover { background-color: #FFFFFF; height: 100%; opacity: 0.4; position: fixed; width: 100%; z-index: 9000; } The goal is to have it cover the entire visi ...

Ways to display a div when a drop-down box is clicked

How can I make a dropdown box that displays 'Yes' and 'No' options? When 'Yes' is selected, how do I show another div on the page? ...

Is it possible to transfer a massive number of files using node.js?

I need to asynchronously copy a large number of files, about 25000 in total. I am currently using the library found at this link: https://github.com/stephenmathieson/node-cp. Below is the code snippet I am using: for(var i = 0; i < 25000; i++ ...

Navigate the speech bubble tail by moving or rotating it with your mouse

For my project, I am working on creating a dynamic speech bubble that can be dragged around the corner of the bubble with the mouse. The goal is for the tip of the speech bubble to rotate automatically based on its position. Below is a snippet of my code: ...

Having trouble with preventDefault() not working during a keyup event?

I am struggling to make preventDefault() function properly. Here are a few variations of the code that I have attempted: First: $(document).keyup(function (evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode == 192) { ...

Determining the margin-left value of a centrally positioned table

I have a table with variable columns, meaning the columns of the table are dynamic. The number of columns will keep changing, causing the table to be centralized and the margin-left value to adjust accordingly. Now, I need to calculate the margin-left val ...

What is the best way to make a gradient fill and rounded border with CSS?

I am interested in creating a gradient and rounded border similar to the top bar on Instagram. Although I know how to create a rounded and solid border, this one utilizes a gradient. It appears that Instagram uses a canvas, but I am wondering if it can b ...

Sending an image to a Kendo popup window triggers a [Request Uri too long 414] error message

On my webpage, I have a Kendo grid that is filled with images and a button labeled "Graph Map". https://i.stack.imgur.com/DyGVs.png Whenever the "Graph Map" button is clicked, a new window pops up displaying the image from the first record in the grid. By ...

Contrasting results when logging an element in Chrome versus IE

Running the script below in Internet Explorer gives the expected output for console.log(target_el): <div class="hidden"></div> However, when run in Chrome, the output changes to: <div class="visible"></div> To add a humorous twi ...

Manually initializing Angular bootstrap with async in the Angular script tag

I am encountering an issue when trying to asynchronously download the Angular script in my application and manually bootstrap the application upon loading. The error message states: Failed to instantiate module wt due to: Error: [$injector:modulerr] htt ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

Choosing different elements using identical classes in JQuery

Struggling with a coding problem that seems like it should be an easy fix, but can't quite figure it out. The HTML code I have is as follows: <section class="actualite"> <div class="actualite-text"> <h3 class="title"&g ...

Refreshingly modernizing SVG in Angular

I've been facing a challenge in my Angular application where I am trying to dynamically add paths to an SVG element within an HTML file. The issue is that even though the paths are getting added to the DOM, they are not showing up in the browser when ...

Cannot display GIF file from the SRC directory in a React application

I am trying to display a gif from the "/src/images" folder in my component, but I keep getting my "old" value displayed instead. What could be causing this issue? Snippet from Danke.js site: import Confetti from "../images/confetti.gif"; <Box sx={{ ju ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

What could be causing the sluggish performance of my JavaScript code?

Could someone offer insight into why my JavaScript code is performing slowly? Are there any optimizations I can implement to improve its speed? Thank you! $(document).ready(function() { /* Trigger animation when window is scrolled */ $(window).scroll( ...

What is the process for retrieving a value from JSON utilizing JavaScript?

Unfortunately, I am completely stumped when it comes to Javascript. I'm attempting a few solutions based on online resources. If anyone could offer some assistance, that would be greatly appreciated. Below is the JSON data provided. It has been conde ...

Can we create a collection of Vue highcharts components in a library format?

I am in search of an answer, with hope that it lies here. I have used the following: "vite": "^2.7.13", "highcharts": "^9.3.3", "highcharts-vue": "^1.4.0" I aim to create a library of Vue compon ...

Having difficulty assigning a selected value in select2 using JavaScript with Ajax mode

I am trying to use a select2 element that loads data from a database using ajax. My goal is to load the value from the database and have it selected as the default value in edit mode. However, I am encountering issues with using the trigger function to ach ...