Reputation: 669
I'm attempting to apply an opacity change on my LI elements by toggling the 'active' class, but neither mouse events or hover are working. Looks like a simple fix but i can't figure out why.
jquery
$( document ).ready(function() {
$('nav.li').mouseenter(function() {
$(this).addClass("active");
});
$('nav.li').mouseleave(function() {
$(this).removeClass("active");
});
$("nav.li").hover(function () {
$(this).toggleClass("active");
});
});
css
nav.li.active {
opacity: .7;
}
html
<nav>
<ul>
<li class="about_link">...</li>
<li class="contact_link">...</li>
<li>...</li>
</ul>
</nav>
Thanks
Upvotes: 1
Views: 844
Reputation: 12508
JavaScript:
Change your selector from:
$('nav.li')
to:
$('nav li')
Currently, your selector is targeting a <nav>
element with a class of li. I think you want to target the <li>
elements inside the <nav>
element.
You can optimize your jQuery by chaining the calls together as well:
// Shorthand document ready...
$(function () {
$('nav li').on('mouseenter', function() {
$(this).addClass("active");
}).on('mouseleave', function() {
$(this).removeClass("active");
});
});
CSS:
You'll need to modify your CSS accordingly too:
nav li.active {
opacity: 0.7;
}
You may want to consider expanding this to include vendor prefixes as well for maximum compatibility:
nav li.active {
/* IE 8 - 9 */
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=70)";
/* IE 5, 6, 7, 8, 9 */
filter: alpha(opacity=70);
/* Older than Firefox 0.9 */
-moz-opacity:0.7;
/* Safari 1.x (pre WebKit!) */
-khtml-opacity: 0.7;
/* Modern!
* Firefox 0.9+, Safari 2?, Chrome any, Opera 9+, IE 9+
*/
opacity: 0.7;
}
Upvotes: 1
Reputation: 38102
Your don't need the .
here between nav
and li
, so you can change:
$('nav.li')
to:
$('nav li')
Final code look like:
$( document ).ready(function() {
$("nav li").hover(function () {
$(this).toggleClass("active");
});
});
Your current selector $('nav.li')
is matching the <nav>
element with class li
. You also need to change your css to:
nav li.active {
opacity: .7;
}
Upvotes: 1