Reputation: 725
I am trying to add a background color to the main link , which shows a sub menu. for now only sub menu is displayed, as soon as mouse leaves the main link, the color goes back to original background color.
<nav>
<ul id="nav">
<li><a href="index.php">home</a>
</li>
<li><a href="intro.php">intro</a>
</li>
<li id="services"><a href="#">services</a>
<ul id="subMenu">
<li><span>one</span></li>
<li><span>two</span></li>
</ul>
</li>
<li><a href="contact.php">contacts</a>
</li>
</ul>
</nav>
<style>
#services {background:yellow;}
#subMenu {position:absolute;display:none;width:250px;}
#subMenu li {border:none;display:list-item!important;width:100%;background:#e13b30;}
#subMenu li span {color:#fff!important;line-height:50px;}
.bgRed {background-color:#e13b30;}
</style>
<script>
$(function(){
$('#nav #services').hover(
function () {
//show its submenu
$('#services', this).stop().addClass('bgRed'),
$('ul', this).stop().slideDown(100);
},
function () {
//hide its submenu
$('ul', this).stop().slideUp(10);
}
);
});
</script>
Upvotes: 0
Views: 221
Reputation: 2589
You can achieve this from CSS also and there is no need of script.. Please check this Fiddle
Upvotes: 0
Reputation: 43156
add the following to your script
$('#submenu').hover(
function () {
//highlight parent
$(this).parent().addClass('bgRed');
},
function () {
//un - highlight parent
$(this).parent().removeClass('bgRed');
}
);
update: Fiddle
well after your weird update of removing removeClass
from the question, i checked the code in a fiddle,
in the below code
$('#services', this).stop().addClass('bgRed')
you are passing this
as the context. so JQuery will search for element with id services
inside this
, which refers to the #services
element itself. hence it won't work.
also stop()
seems to be unnecessary..
Upvotes: 1
Reputation: 2388
Use something like this
$('#nav #services').hover(
function () {
//show its submenu
$(this).find("a").toggleClass('bgRed').stop();
$('ul', this).stop().slideDown(100);
},
function () {
//hide its submenu
$(this).find("a").toggleClass('bgRed').stop();
$('ul', this).stop().slideUp(10);
}
);
Also you have an error on your class definition
.bgRed{background-color,#e13b30;}
Should be
.bgRed{background-color:#e13b30;}
Notice the :
Upvotes: 2