Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running javascript code on page load, without using the onload tag

Tags:

javascript

How can I run a JavaScript code when the page loads without using the onload tag?

I'm trying to run this script:

<script type="text/javascript">
function displayLightbox() {
    document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'
}
</script>

That displays a lightbox.

like image 466
Or Weinberger Avatar asked Jan 18 '11 09:01

Or Weinberger


1 Answers

Like this:

window.onload = function WindowLoad(event) {
    alert("Page is loaded");
}

Edit: if some other code is also using window.onload after that script then it will be "overwritten" - to make sure it's executed (and abort any other onload) put it in the bottom of the page.

Edit 2: On second thought, you better add onload listener instead of overwriting it:

<script type="text/javascript">
if (window.addEventListener) { // Mozilla, Netscape, Firefox
    window.addEventListener('load', WindowLoad, false);
} else if (window.attachEvent) { // IE
    window.attachEvent('onload', WindowLoad);
}

function WindowLoad(event) {
    alert("Another onload script");
}
</script>

This will prevent any conflicts with existing code and is more cross browser as far as I can tell.

Live test case is available here: http://jsfiddle.net/yahavbr/GZPTG/ tested for IE8, Chrome and Firefox (latest versions) feel free to test for more.

like image 82
Shadow Wizard Hates Omicron Avatar answered Oct 31 '22 15:10

Shadow Wizard Hates Omicron