Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

javascript - Adding Events via the DOM

Options
  • 28-06-2003 2:35pm
    #1
    Registered Users Posts: 2,119 ✭✭✭


    Hey all,

    I'm building a DOM based menu, so wondering how too attach an event to an object.

    e.g. i'd like to attache onMouseover to all the DIVs in a DIV with the id MENU.

    Can you do that, or does anyone have any alternatives or pointers.

    Thanks,

    - Kevin


Comments

  • Closed Accounts Posts: 304 ✭✭Zaltais


    Hey p,

    It's actually not too hard to engineer, so I've bashed it together in the sample below.

    Shout, if it doesn't work properly or if you want me go though it, unfortunately I don't have time right now to go too far into details...

    [PHP]
    <html>
    <head>
    <script>
    <!--
    function start(){
    if( document.getElementById ) {
    var x = document.getElementById('menu');
    var y = x.getElementsByTagName("div");

    for (var i = 0; i < y.length; i++){
    y.setAttribute('onmouseover', 'change(this)');
    y.setAttribute('onmouseout', 'revert(this)');
    }

    } else {
    window.alert('Not supported');
    }

    }

    function change(a){
    a.style.backgroundColor = "Black";
    a.style.color = "White";
    }

    function revert(a){
    a.style.backgroundColor = "White";
    a.style.color = "Black";
    }
    -->
    </script>
    </head>
    <body onLoad="start();">
    <div id="menu">
    <div>DIV number 1</div>
    <div>DIV number 2</div>
    <div>DIV number 3</div>
    </div>
    </body>
    </html>
    [/PHP]


  • Registered Users Posts: 2,119 ✭✭✭p


    Hey, that looks perfect.

    I had to mae a change, to get it to work in IE5. Applying the function directly, like so, seems to work:

    [PHP]
    y.onmouseover = function () { change(this); };
    y.onmouseout = function () { revert(this); };
    [/PHP]

    Thanks.

    - Kevin


Advertisement