Matthew Williams
Matthew Williams

Reputation: 49

Execute Javascript automatically?

I have this script that greys out the entire website and brings up a dialogue box when the text 'showPopUp' is clicked. My question is how can i get this script to execute automatically on page load?

Script:

<script type="text/javascript">
    function showPopUp(el) {
        var cvr = document.getElementById("cover")
        var dlg = document.getElementById(el)
        cvr.style.display = "block"
        dlg.style.display = "block"
        if(document.body.style.overflow = "hidden") {
            cvr.style.width = "1024"
            cvr.style.height = "100&#37;"
        }
    }

    function closePopUp(el) {
        var cvr = document.getElementById("cover")
        var dlg = document.getElementById(el)
        cvr.style.display = "none"
        dlg.style.display = "none"
        document.body.style.overflowY = "scroll"
    }
</script>

Upvotes: 0

Views: 125

Answers (3)

davidbuzatto
davidbuzatto

Reputation: 9444

The better aproach is to use the "document.ready" event, not window.load, because the load event is just triggered after ALL page resources are loaded, while the ready event is triggered after the document is ready (all HTML is loaded and the DOM is ready).

Note that the "document.ready" event is not an event implemented in JavaScript but "emulated" by some JavaScript libraries like jQuery.

Instead of writing an example, I got these two links, take a look:

Upvotes: 0

Fred Wuerges
Fred Wuerges

Reputation: 1965

window.onload = function() {
  showPopUp('yourObjeID');
};

or

<body onload="showPopUp('yourObjeID');">

or insert script before body ends:

...
<script>
    showPopUp('yourObjeID');
</script>
</body>
</html>

Upvotes: 3

Dan Dascalescu
Dan Dascalescu

Reputation: 151893

Use window.onload. Documentation at https://developer.mozilla.org/en-US/docs/DOM/window.onload

Upvotes: 1

Related Questions