简体   繁体   中英

Display Popup on page load using JavaScript

The following is my HTML for popup:

<div id="overlay">

     <div>
        <header>
            <h2 class="modalHeader">Disclaimer:</h2>
        </header>
        <p>"xxxxxxxx"</p>           
        <button id="acceptButton" onclick="overlay()">Accept</button>

     </div>
</div>

The following is my CSS for the popup that is of concern:

#overlay {
     visibility:   hidden;
     /*position: absolute;*/
     left:         0px;
     top:          0px;
     width:        100%;
     height:       100%;
     text-align:   justify;
     z-index:      1000;
     font-family:  candara;

}

The following is my JavaScript to make popup appear on pageload:

function popup{
var overlay = document.getElementById("overlay");
overlay.style.visibility = "visible";
}

I am trying to change the css visibility: hidden to visibility: visible ....why is this not working?

  • the questions have flaws, if you make "overlay" hidden initially , then what will click ?
  • on clicking the button "accept" you are calling a function which is not there .
  • the function is defined and declared always using parenthesis () , which is missing in your question .

Solution 1: I have given id to the p element as p1 in my demo , initially made it hidden by using visibility: hidden; 2: on clicking the button calling appropriate function which is making the paragraph visible .

DEMO : http://jsfiddle.net/5aww1sef/2/

<script>
function overlay() {
    var overlay = document.getElementById("p1");
    overlay.style.visibility = "visible";
}
</script>


<div id="overlay">
     <div>
        <header>
            <h2 class="modalHeader">Disclaimer:</h2>
        </header>
        <p  id="p1">"xxxxxxxx"</p>           
        <button id="acceptButton" onclick="overlay()">Accept</button>

     </div>
</div>

#overlay {
     left:         0px;
     top:          0px;
     width:        100%;
     height:       100%;
     text-align:   justify;
     z-index:      1000;
     font-family:  candara;
}
#p1{
     visibility:   hidden;
}

Missing syntax here - with parentheses - also you'll need to call popup() as the function to call on click or when you need it. I assume the button inside the overlay is to do another function like close the overlay right?

function popup() {
var overlay = document.getElementById("overlay");
overlay.style.visibility = "visible";
}

Better use display:none; as visibility:hidden; take up space on the page. Use the display property to create invisible elements that do not take up space

Demo

https://jsfiddle.net/5sep0y5f/

Code

document.getElementById('overlay').style.display = 'block'; // show

document.getElementById('overlay').style.display = 'none'; // hide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM