Results 1 to 2 of 2

Thread: Example of DOM event attachment if possible

  1. #1
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Question Example of DOM event attachment if possible

    Hmm... anyone out there have a very simple example of DOM event attachment in action?

    I mean super simple, like perhaps if I wanted a mouseover of one element to affect the innerhtml of another.

    I'd love to see a basic event handler/attachment

    - Ben
    Last edited by Falkon303; 02-21-2009 at 07:41 PM.
    document.write is document.wrong

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I'm not sure what the question is exactly. Say you create two span elements and a function:

    Code:
    var a = document.createElement('span'),
        b = a.cloneNode(false);
    function f(){b.firstChild.nodeValue += 'Hello World! ';}
    add in some text nodes:

    Code:
    a.appendChild(document.createTextNode('Mouse Me!'));
    b.appendChild(document.createTextNode('\xa0'));
    attach/add function f to span a as a mouseover listener:

    Code:
    if (window.addEventListener)
     a.addEventListener('mouseover', f, false);
    else if (window.attachEvent)
     window.attachEvent('onmouseover', f);
    and Bob's your uncle. But let's wrap it all up in a function to execute when the page loads so that it can actually do something (in this case append its elements to the body):

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    function myload(){
     var a = document.createElement('span'), b = a.cloneNode(false);
     function f(){b.firstChild.nodeValue += 'Hello World! ';}
     a.appendChild(document.createTextNode('Mouse Me!'));
     b.appendChild(document.createTextNode('\xa0'));
     if (window.addEventListener)
      a.addEventListener('mouseover', f, false);
     else if (window.attachEvent)
      a.attachEvent('onmouseover', f);
     document.body.appendChild(a);
     document.body.appendChild(b);
    }
    
    if (window.addEventListener)
     window.addEventListener('load', myload, false);
    else if (window.attachEvent)
     window.attachEvent('onload', myload);
    </script>
    </head>
    <body>
    
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

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