Adding event listener problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bugboy
    New Member
    • Sep 2007
    • 160

    Adding event listener problem

    i'm trying to avoid inline event handlers by creating a listener. What i'm trying is based on reading this: http://www.quirksmode.org/js/events_advanced.html

    I can't figure out what i'm doing wrong.. here is an example which i want to turn a div's background colour to grey when clicked but it doesn't work :(

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html><head><title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    document.getElementById("box").addEventListener('click',doSomething,false);
    function doSomething() {
    	this.style.backgroundColor = '#555555';
    }
    </script>
    </head>
    <body>
     <div id="box" style="background-color:blue; height:200px; width:200px;">&nbsp;</div>
    </body>
    </html>]
  • bugboy
    New Member
    • Sep 2007
    • 160

    #2
    maybe this i far too simplified.. i'll add another question to this one... if using inline event handlers is so out of date why can't i find a strong tutorial on the current state of the art way of doing this. The quirksmode article seems detailed but it never seems to put it all together in a way that i can see the application of it in practice.

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      two things
      a) Internet Explorer doesn't support addEventListene r(), search for the addEvent() functions (workaround)
      b) if the element doesn't exists yet (i.e. not yet loaded) the event can't be attached. you have to delay the event attaching until the page is fully loaded, or append the script element at the end of the content.

      Comment

      • bugboy
        New Member
        • Sep 2007
        • 160

        #4
        Thanks, Exactly what i needed!

        Comment

        Working...