Benjamin Laffel Hooge
Benjamin Laffel Hooge

Reputation: 15

Can't get hasClass to work properly with condition

I can't seem to wrap my head around this: http://jsfiddle.net/pvyaL/

    $(function () {
        if (!$(this).hasClass('selected')) {
            $('.navigation li').hover(function () {
                $(this).find('a').attr('class', 'hovering');
            },
            function () {
                $(this).find('a').attr('class', '');
            });
        };
    });

Basically what I want, is to ignore the hover class change, if the element already has a specific class (in this case; 'selected').

What am I missing?

Upvotes: 0

Views: 139

Answers (3)

Jon
Jon

Reputation: 437336

That code has several mistakes:

  • this refers to the document, not on any li element.
  • Setting classes with .attr is a really bad choice -- addClass, removeClass and toggleClass exist exactly for this purpose.
  • You do not even need jQuery for this, as it can be done with pure CSS.

In jQuery form, what you want is more like

$('.navigation li:not(.selected)').hover(
function () {
    $(this).find('a').addClass('hovering');
},
function () {
    $(this).find('a').removeClass('hovering');
});

If you want to make the script respond to changes in the selected class dynamically another version would be the solution:

$('.navigation li').hover(
function () {
    if(!$(this).hasClass('selected')) $(this).find('a').addClass('hovering');
},
function () {
    if(!$(this).hasClass('selected')) $(this).find('a').removeClass('hovering');
});

Of course there is no reason to do this with jQuery; pure CSS will suffice:

.navigation li:not(.selected):hover a {
    /* your styles go here */
}

The :not selector is not supported by IE8, but if that is a problem you can work around it using the set/revoke trick.

Upvotes: 3

Niels van der Wal
Niels van der Wal

Reputation: 53

$(this) is in your code 'nothing', look at http://jsfiddle.net/pvyaL/2/

I also changed this:

if (!$(this).find('a').hasClass('selected')) {

So the check is on the <a>, not on the <li>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$(function() {
    $('.navigation').on('mouseenter', 'li:not(.selected)', function() {
        $(this).find('a').attr('class', 'hovering');
    }).on('mouseleave', 'li:not(.selected)', function() {
        $(this).find('a').attr('class', '');
    })
});

or

$(function() {
    $('.navigation li').hover(function() {
        if (!$(this).hasClass('selected')) {
            $(this).find('a').attr('class', 'hovering');
        }
    }, function() {
        if (!$(this).hasClass('selected')) {
            $(this).find('a').attr('class', '');
        }
    });
});

Upvotes: 0

Related Questions