0

HTML

<div>
    <ul class="navBar"> 
        <li class="selected"><a href="#">HOME</a></li>
        <li><a href="#">WORKS</a></li>
        <li><a href="#">ARTICLES</a></li>
        <li><a href="#">ABOUT</a></li>
    </ul>
</div>

CSS

.selected{
    background-color: #CCCCCC;
}

.onHover{
    display: block;
    background-color: #0088FF;
}

JAVASCRIPT

$(function() {
        $("ul.navBar li a").hover(
            function(){
                $(this).addClass("onHover");
            },
            function(){
                $(this).removeClass("onHover");
        });
    });

What I want here is the javascript to not add 'onHover' class to the HOME link when hovered over, just the other three links.

vep temp
  • 249
  • 1
  • 6
  • 18
  • Are you only trying to change the styling (background color) or do you want to do more things with this? If you're just trying to change the styling, don't bother using Javascript - the `:hover` pseudoclass is more than qualified – Ian Mar 20 '13 at 05:05

2 Answers2

1

You can use not() selector to not allow the item to be picked.

$(function() {
    $("ul.navBar li:not(.selected) a").hover(
        function(){
            $(this).addClass("onHover");
        },
        function(){
            $(this).removeClass("onHover");
    });
});

BUT you can do this with a pure CSS only solution if you really wanted. No JavaScript is needed.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Use the jQuery :not() selector to not include the "selected" class. Also better to use event delegation .on() rather directly binding the event to elements ie. .hover().

See http://api.jquery.com/not-selector/ for more information on using :not().

$(function () {
    $(document).on('mouseenter', 'ul.navBar li:not(.selected) a', function () {
        $(this).addClass('onHover');
    });
    $(document).on('mouseleave', 'ul.navBar li:not(.selected) a', function () {
        $(this).removeClass('onHover');
    });
});

See fiddle: http://jsfiddle.net/4rZ3D/

Amy
  • 7,388
  • 2
  • 20
  • 31