Delay in CSS dropdown menu with Javascript

Discussion in 'JavaScript' started by ldor, Oct 19, 2010.

  1. #1
    Hi,

    I have a dropdown CSS menu with a bit of Javascript. I need to add a delay to it so that the menu does not disappear immediately when the mouse is moved away. I found in the forums that it should be done using setTimeout function. However it does not work for my menu, it closes without any delay. I don't know Javascript, so I can't figure out where the mistake is. Below I paste two pieces of code, the original one and the one with setTimeout. Can anybody explain me what is wrong and how to correct it?

    The original code:

    <script type="text/javascript"><!--//--><![CDATA[//><!--
    sfHover = function() {
    var sfEls = document.getElementById("mainlevelmainnav").getElementsByTagName("LI");
    for (var i=0; i<sfEls.length; i++) {
    sfEls.onmouseover=function() {
    this.className+=" sfhover";
    }
    sfEls.onmouseout=function() {
    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
    }
    }
    if (window.attachEvent) window.attachEvent("onload", sfHover);
    //--><!]]></script>


    Modified code with setTimeout to have a 500 ms delay:

    <script type="text/javascript"><!--//--><![CDATA[//><!--
    sfHover = function() {
    var sfEls = document.getElementById("mainlevelmainnav").getElementsByTagName("LI");
    for (var i=0; i<sfEls.length; i++) {
    sfEls.onmouseover=function() {
    this.className+=" sfhover";
    }
    sfEls.onmouseout=setTimeout(function() {
    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }, 500);
    }
    }
    if (window.attachEvent) window.attachEvent("onload", sfHover);
    //--><!]]></script>
     
    ldor, Oct 19, 2010 IP