Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Function called by onload event not executing fully

    Hi everyone,

    I am having issues with the following bit of code:

    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.

    Code:
    // 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

  • #2
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,864
    Thanks
    160
    Thanked 2,224 Times in 2,211 Posts
    Could you post your html code also?
    Edit:
    Umm... looks strange, though the following would work
    Code:
    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());
    Last edited by abduraooft; 01-28-2009 at 03:03 PM.
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

  • #3
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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:

    Code:
    if (window.attachEvent) window.attachEvent("onload", test);
    Thanks again,
    Chris


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •