...

View Full Version : Function called by onload event not executing fully



Zakalwe
01-28-2009, 02:45 PM
Hi everyone,

I am having issues with the following bit of code:



function test(){
window.alert("Alert1");
var testvar = document.getElementById("topMenu").getElementsByTagName("li");
window.alert("Alert2");
}

if (window.attachEvent) window.attachEvent("onload", test());


When the page loads "Alert1" is being displayed however "Alert2" is not.

If I call the function from within the page itself (example below) both "Alert1" and "Alert2" are being displayed.



// It works this way!
<script type="text/javascript">
test();
</script>


I have a funny feeling that this problem stems from my limited knowledge of Javascript (I'm bound to be doing something wrong!), any help or advice that you can give would be much appreciated.

Cheers,
Chris

abduraooft
01-28-2009, 02:58 PM
Could you post your html code also?

Umm... looks strange, though the following would work

window.onload=function test(){
if (!window.attachEvent) return;
window.alert("Alert1");
var testvar = document.getElementById("topMenu").getElementsByTagName("li");
window.alert("Alert2");
}
//if (window.attachEvent) window.attachEvent("onload", test());

Zakalwe
01-28-2009, 03:11 PM
Thanks for the quick reply, looks like I posted for help a little prematurely though (although I had been stuck for hours!).

I managed to get it working by removing the parenthesis after the function name when attaching the event. The working code looks like this:



if (window.attachEvent) window.attachEvent("onload", test);


Thanks again,
Chris



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum