Ankur
Ankur

Reputation: 51100

How to add a conditional to jQuery .hover()

I want to use the jQuery hover function and can do so with no problem.

 $(".tag").hover(function() { $(this).addClass("tag-over"); }, function() { $(this).removeClass("tag-over"); });

However in some circumstances I will have already added the tag-over class due to a click event, but I don't want it remove when the user removes the mouse.

How do I only perform the addClass() and rmeoveClass() if the tag-over class is not already attached to the element.

Please let me know if that explanation is no good.

Upvotes: 2

Views: 1721

Answers (5)

S L
S L

Reputation: 14318

Not elegant solution though here.

Bad thing about it, it adds click class to check.

$('.tag').hover(
    function (){
        $(this).addClass("tag-over"); 
    },
    function (){
        if(!$(this).hasClass('clicked')){
            $(this).removeClass("tag-over"); 
        }
    }
).click(function (){
            $(this).addClass('click');
        })

Upvotes: 0

Kent
Kent

Reputation: 2960

why don't you try to add class tagover for click event and tag-over for hover event?

Hope this helps

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237865

I think something like this should do it:

$('.tag').hover(function() {
    var $this = $(this);

    if ($this.hasClass('tag-over')) {
        $this.data('tag-over-existed', true);
    } else {
        $this.addClass('tag-over');
    }
}, function() {
    var $this = $(this);

    if (!$this.data('tag-over-existed')) { // i.e. if we added the class ourselves
        $this.removeClass('tag-over');
    }

    $this.removeData('tag-over-existed');
});

This uses the data method to store information about a particular element.

Upvotes: 2

user578895
user578895

Reputation:

You actually want to probably have a different selector for the click event: tag-focus or something like that. That way your element can have both classes and it won't matter, much simpler to keep track of.

Upvotes: 2

Kristoffer Lundberg
Kristoffer Lundberg

Reputation: 876

If I understand your question, you can use :not(), which I think would be the best of dealing with this.

$(".tag:not(.tag-over)").hover(function() { $(this).addClass("tag-over"); }, function() { $(this).removeClass("tag-over"); });

Upvotes: 2

Related Questions