abdul raziq
abdul raziq

Reputation: 859

i am creating javascript drop down menu but its not working as expected?

here is my html and please check jsfiddle this is not working as expected

<div id="menu1" class="menu">
<a href="#" id="home">Home</a>
<ul id="homesection">
<li>Item one</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>
</div>
<div id="menu2" class="menu">
<a href="#" id="gallery">Gallery</a>
<ul id="gallerysection">
<li>Item one</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>
</div>
<div id="menu3" class="menu">
<a href="#" id="about">About</a>
<ul id="aboutsection">
<li>Item one</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>
</div>
<div id="clear"> </div>

this is my css codding

.menu{
float:left;


}
ul{
position:absolute;
width:150px;
z-index:500;
display:none;
}
ul,li{
margin:0;
padding:0;

}
li{
list-style-type:none;

padding:3px;
color:gray;
background-color:"lightblue";
}
a{
text-decoration:none;
font-size:2em;
color:gray;
font-family:verdana;
display:block;
margin-right:15px;
}
#clear{
clear:both;
}

and this is my javascript

var links = document.getElementsByTagName("a");
var len = links.length;

for(var i = 0; i<len; i++){

links[i].onmouseover = handleHover;

}
function handleHover(){
var uls = document.getElementsByTagName("ul");
var len = uls.length;
for(var i=0; i<len;i++){
uls[i].style.display = "none";
}
var e = window.event;
var target = e.srcElement.id;
target += "section";
var mainmenu = document.getElementById(target);
mainmenu.style.display = "block";
mainmenu.onmouseout = function(){

mainmenu.style.display = "none";

}

}

its droping down but when cursor passes first menu item the menu disappears ?

Upvotes: 0

Views: 42

Answers (1)

francisco.preller
francisco.preller

Reputation: 6639

You forgot to close handleHover(), see the working fiddle below

http://jsfiddle.net/3tFKb/4/

Edit If you change the mouseover and mouseout to mouseenter and mouseleave, then it works as it is meant to.

Working code:

var links = document.getElementsByTagName("a");
var len = links.length;

for(var i = 0; i<len; i++){
    links[i].onmouseenter = handleHover;    
}

function handleHover(){
    var uls = document.getElementsByTagName("ul");
    var len = uls.length;
    for(var i=0; i<len;i++){
        uls[i].style.display = "none";
    }
    var e = window.event;
    var target = e.srcElement.id;
    target += "section";
    var mainmenu = document.getElementById(target);
    mainmenu.style.display = "block";
    mainmenu.onmouseleave = function(event){
        mainmenu.style.display = "none";
    }
}

Upvotes: 1

Related Questions