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 Coder
    Join Date
    Aug 2006
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    window.onload loads before content

    I am a total noob to javascript. What I am trying to do is to change links dynamically if javascript can be run on the user's computer. The code that I have come up with to do this is:

    Code:
    function changeLinks(eleId) {
    	if (document.getElementById) {
    		var textLink = document.getElementById(eleId);
    		if (textLink.getAttribute('href') == "#") {
    			textLink.setAttribute('href', "javascript:showdiv('hide');");
    		}
    	}
    }
    
    window.onload = changeLinks('show');
    This is all fine and good except that I keep getting an error of "textLink has no properties" and the script doesn't work.

    If I get rid of the "window.onload" event and call the function in script tags at the bottom of my page, it works fine. Just not when I try to have it do it automatically when the page loads via this external script.

    Just for the record, the code above is the entire external javascript file, and I am calling it in my HTML with this line:

    Code:
    <script type="text/javascript" src="javascript.js"></script>
    I don't have a clue as to what I am doing wrong. It seemed to me like it should work.

    Any help?

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    The problem lies in this line:
    Code:
    window.onload = changeLinks('show');
    You're setting window.onload to the return value of calling the function changeLinks with the argument 'show'.

    In other words, you're doing the function call first, and then adding the result from it as the load even handler. Try the following instead:
    Code:
    window.onload=function(){changeLinks('show')};
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    New Coder
    Join Date
    Aug 2006
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts
    That did it. Wow. I would have never figured that out!

    Thanks a lot!

    By the way, can you recommed any books for the absolute noob on javascript? I went out and got "Beginning Javascript with DOM Scripting and AJAX", but it is really hard to follow. I wouldn't say that it is for the beginner at all!


  •  

    Posting Permissions

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