Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate to body onload = (string) for Javascript

I'm (somewhat) new to JavaScript and I'm writing a timing plugin that requires

<body onload="mktClock_standard(); setInterval('mktClock_standard()', 1000 ); mktClock_military(); setInterval('mktClock_standard()', 1000 )">

And I was wondering if there's a way to do that, but in JavaScript, like using window.onload or something. I tried simply:

window.onload = mktClock_standard(); setInterval('mktClock_standard()', 1000 ); mktClock_military(); setInterval('mktClock_standard()', 1000 )

But obviously there are so many wrong syntax errors and stuff, so... I went to Google but I could not find anything relating to my problem. Any ideas?

like image 599
ModernDesigner Avatar asked Mar 13 '26 12:03

ModernDesigner


2 Answers

window.onload is the exact same thing as the onload attribute, but it expects a function:

window.onload = function() {
    mktClock_standard(); 
    setInterval('mktClock_standard()', 1000 ); 
    mktClock_military(); 
    setInterval('mktClock_standard()', 1000 )
}

Actually, when you add code to attributes like <body onload="code...">, the browser will treat them as if there were a wrapping anonymous function.

Also, modern browsers support the DOMContentLoaded event, which is similar, but fires ealier. It fires as soon as the DOM is loaded, while window.onload waits for other resources (such as images) to be loaded. To bind to DOMContentLoaded, use addEventListener:

document.addEventListener('DOMContentLoaded', function(evt) {
    // event handler code here
});

(The above won't work in IE8 and earlier)

like image 134
bfavaretto Avatar answered Mar 16 '26 01:03

bfavaretto


You want to use a function declaration:

window.onload = function() {
    mktClock_standard();
    setInterval('mktClock_standard()', 1000 ); 
    mktClock_military(); 
    setInterval('mktClock_standard()', 1000 )
}
like image 25
saml Avatar answered Mar 16 '26 00:03

saml



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!