Search code examples
javascriptdrop-down-menudom-eventsmenubardhtml

Unique JavaScript/DHTML Menu: Onmouseover/onmouseout scripting logic challenges


I am attempting to create a JavaScript menu that would employ the following HTML:

<table id="mainMenu">
  <tr>
    <td id="mainMenu1">Item 1</td>
    <td id="mainMenu2">Item 2</td>
    <td id="mainMenu3">Item 3</td>
  </tr>
</table>

<table id="subMenuA" style='hidden';>
  <tr>
    <td>Subitem A1</td>
    <td>Subitem A2</td>
    <td>Subitem A3</td>  
  </tr>
</table>
<table id="subMenuB" style='hidden';>
  <tr>
    <td>Subitem B1</td>
    <td>Subitem B2</td>
    ...

When #mainMenu1 onmouseover, I want #subMenuA.style='visible'.
When #mainMenu1 onmouseout, I want #subheaderA.style='hidden'.
When #subMenuA onmouseout, I want #subheaderA.style='hidden'.

Note that traditional drop-down scripts don't work because the two menus are two separate elements and there is a small distance between them. It's therefore necessary to "bridge the gap" between the two elements. How to do this??

Could anyone suggest a basic JavaScript code to get this working? Even just the logic/idea would be great. I would really appreciate it!


Solution

  • Updated answer: http://jsfiddle.net/imsky/zcwJt/4/

    var $ = function(el) {
        return document.getElementById(el)
    };
    
    var menu_timer;
    
    $("item1").onmouseover = function() {
        window.clearTimeout(menu_timer);
        $("menu1").style.display = "block";
    }
    
    $("menu1").onmouseover = function() {
        window.clearTimeout(menu_timer);
    }
    
    $("menu1").onmouseout = function(e) {
        window.clearTimeout(menu_timer);
        if (!parent(e.relatedTarget, this)) {
            var menu = this;
            menu_timer = window.setTimeout(function() {
                menu.style.display = "none";
            }, 1000)
        }
    }
    
    var parent = function(el, p) {
        if (!el) {
            return false;
        }
        if (el !== p) {
            while (el.parentNode) {
                el = el.parentNode;
                if (el == p) {
                    return true;
                }
            }
        }
        else {
            return true;
        }
        return false;
    }