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 5 of 5
  1. #1
    New Coder
    Join Date
    May 2009
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Unhappy External event handlers won't work

    I'm a JS noob and I've been at this for days... (trying to set up external event handlers)

    When I register an event handler directly into the HTML tag everything works fine, but I'm trying to register them from the external JS file where the function is, and that doesn't work at all. I've read that this is called the "traditional method" and that it should work.

    I've tried it a million different ways, but what I'm putting below AFAIK is correct... but it just doesn't work. I've tried it in Firefox, IE, and Chrome - and used the "Inspect element" feature in Chrome, and am not getting any error messages.

    Here is just a simple example of what I'm trying to do - its extremely basic, I know, but I just can't figure out why it won't work.

    HTML:

    Code:
    <!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
    <title>SITE</title>
    <link rel="stylesheet" type="text/css"
    href="sitecss.css" />
    <script type="text/javascript" src="sitejs.js"></script>
    </head>
    <body>
    
    <h1 id="nav">Logo</h1>
    <p id="main">C'mon work!</p>
    
    </body>
    </html>
    JS:

    Code:
    function message(){
    alert('Hello');
    }
    
    foo="document.getElementById('nav')";
    foo.onclick=message;
    -------------------------------------------------


    (Again, it works perfectly when I stick the onclick="message()" event handler directly into the HTML h1 tag, but not when in the external file.)


    I'd really appreciate any help/suggestions. I've been at this for way too long and it's driving me nuts.

  • #2
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    Here ya go:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Test</title>
    <script type="text/javascript">
    // <![CDATA[
    
    function message()
    	{
    	alert("hey");
    	}
    
    function mainOnClick()
    	{
    	alert("you clicked on main");
    	}
    
    function addEventHandler(to_element,event,handler)
    	{
    	if (typeof(handler)=="string") handler = Function(handler);
    	var f = event.substr(0,2);
    	var e = (f=="on"||f=="On"||f=="ON"||f=="oN") ? event.substr(2) : event;
    	to_element.addEventListener ? to_element.addEventListener(event,handler,false) : to_element.attachEvent("on"+event,handler);
    	}
    
    function addMyElementEventHandlers()
    	{
    	addEventHandler(document.getElementById("nav"),"click",message);
    	addEventHandler(document.getElementById("main"),"click",mainOnClick);
    	}
    
    addEventHandler(window,"load",addMyElementEventHandlers);
    
    // ]]>
    </script>
    </head>
    <body>
    
    <div id="nav">my nav</div>
    <div id="main">main</div>
    
    </body>
    </html>
    You can put that JS in an external file and it'll work the same.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • Users who have thanked itsallkizza for this post:

    nxgn (05-27-2009)

  • #3
    New Coder
    Join Date
    May 2009
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts
    whoa no wonder it wouldn't work... its way different than I thought.

    Man I got a lot to learn. Thanks for the quick response too!

  • #4
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    Well there are multiple ways of doing it. But the main differences are:

    - In order to add an event handler to an element in the DOM, that element needs to first be added to the DOM. Essentially this means you need to wait until the document has loaded before manipulating the page. window.onload is the handler you're looking for.
    - addEventHandler() is a function I wrote that will allow you to add multiple event handlers to elements without worrying about placing them all in the same place in your code. There are versions of this in pretty much every JS library out there, but I included this so the code would run standalone. You don't need a function like this because window.onload can be assigned on it's own, but since you plan on adding events to window.onload in an external JS file, it's good practice to use something similar to addEventHandler() so you don't get conflicts down the road.
    - Your foo variable is in fact a string, and an unnecessary one at that. You were on the right track though. This:
    Code:
    foo="document.getElementById('nav')";
    foo.onclick=message;
    should be written as simply:
    Code:
    document.getElementById("nav").onclick = message;
    If you want to put it all together in the simplest fashion, this will work just fine:
    Code:
    function message()
    	{
    	alert("hey");
    	}
    
    window.onload = function()
    	{
    	document.getElementById("nav").onclick = message;
    	}
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #5
    New Coder
    Join Date
    May 2009
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Lightbulb

    heh that's more my speed

    I had this code in originally:
    Code:
    document.getElementById("nav").onclick = message;
    ...but it gave back an error, so i created the var foo (mostly because I've seen that done in a few examples from 'how to' guides).

    Of course the error was actually attaching things to DOM elements that hadn't loaded yet, as you explained. That's interesting. Still haven't got my head around how this all works, but your explanation has gone a long way... thanks for taking the time to break it down for me.

    I had been stuck on this way too long thinking it was something simple, but just didn't know what (and prob never would've guessed). I'll be studying your original code to learn more. Thank you!


  •  

    Posting Permissions

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