Reputation: 33
I am coding a dropdown submenu as below:
<ul id="main_menu">
<li class="enter-top-level">
<a href="#entering">
Enter Data
<ul id="enter_scheme_global">
<li class='submenu'>
<a href="#enter_scheme">
Scheme Details
</a>
</li>
<li class='submenu'>
<a href="#enter_transformer">
Transformer
</a>
</li>
<li class='submenu'>
<a href="#enter_AIS">
AIS
</a>
</li>
<li class='submenu'>
<a href="#enter_GIS">
GIS
</a>
</li>
</ul>
</a>
</li>
I want to give it a animated slideDown and slideUp effect with jquery and I tried the following :
$('a').mouseenter(function() {
$(this).find('ul').slideToggle(500);
$(this).parent('.submenu').css({"background-color" : "#700000"});
});//end $('a').hover function*/
$('a').mouseout(function() {
$(this).find('ul').fadeToggle(500);
$(this).parent('.submenu').css({"background-color" : "#C8C8C8"});
});//end $('a').hover function*/
but without success. Any help anybody.
Upvotes: 0
Views: 68
Reputation: 8858
Try this :
$("a").hover(
function() {
$(this).next('ul').slideToggle(500); // 'next' finds the next occurring element to the current 'a' tag
$(this).next('ul').find('.submenu').css({"background-color" : "#700000"});
}, function() {
$(this).next('ul').slideToggle(500);
$(this).next('ul').find('.submenu').css({"background-color" : "#C8C8C8"});
}
);
Working example : https://jsfiddle.net/9882acxn/4/
Upvotes: 0
Reputation: 11533
There are a couple issues with the code.
First, your HTML needs to be changed. Your top level a
tag wraps all the elements, which would render the children a
elements useless. You also don't need to have two separate functions for the mouseover/mouseout
. You can use the hover()
method. Also, targeting the parent li
will allow the menu to stay open as the mouse is still over it (as opposed the a
element). Here is the working code:
fiddle: http://jsfiddle.net/xf02743m/1/
HTML
<ul id="main_menu">
<li class="enter-top-level"><a href="#entering">Enter Data</a>
<ul id="enter_scheme_global">
<li class='submenu'><a href="#enter_scheme">Scheme Details</a>
</li>
<li class='submenu'><a href="#enter_transformer">Transformer</a>
</li>
<li class='submenu'><a href="#enter_AIS">AIS</a>
</li>
<li class='submenu'><a href="#enter_GIS">GIS</a>
</li>
</ul>
</li>
CSS - hide the submenu first
#enter_scheme_global {
display:none;
}
jQuery
$(".enter-top-level").hover(function () {
$(".enter-top-level ul").slideDown("slow");
$(this).parent().css({"background-color" : "#700000"})
}, function(){
$(".enter-top-level ul").slideUp("slow");
$(this).parent().css({"background-color" : "#C8C8C8"});
});
Upvotes: 1