Prithviraj Mitra
Prithviraj Mitra

Reputation: 11852

click and hover function on same element

I am having a small problem with mouse over/leave/click function.

It's working fine but after clicking the element it's losing the hover function.I can't get the hover function once the element is clicked.

$('.bg').click(function () {
    $(this).unbind("mouseenter mouseleave");
    $('.bg').removeClass('active');

    $(this).addClass('active');

}).hover(function () {    
    $(this).addClass('active');
}, function () {    
    $(this).removeClass('active');
});

jsfiddle --

http://jsfiddle.net/squidraj/SVkBs/1/

Not sure where I am doing the mistake.Thanks.

Upvotes: 0

Views: 2220

Answers (3)

Milche Patern
Milche Patern

Reputation: 20492

$('.bg').click(function () {
    /* remove that following line  */
    $(this).unbind("mouseenter mouseleave");  /* <-- this will UNBIND the 'hover' */
    /* did you remove that previous line ? */
    $('.bg').removeClass('active'); /* <-- this will remove 'active' from .bg */
    $(this).addClass('active');  /* <-- this will add 'active' on this(.bg) */
}).hover(function () {    /* <-- this will try to addClass 'active' on hover .. */
    $(this).addClass('active');
}, function () {    /* <-- this will try to removeClass on the otherHand (callback) */
    $(this).removeClass('active');
});

ps. This function is working all right, you just didn't know what it is supposed to do (unbinding hover events).


do it this way (toggling a class on hover)

$('.bg').hover(
       function(){ $(this).addClass('active') },
       function(){ $(this).removeClass('active') }
)

Upvotes: 1

Russell Zahniser
Russell Zahniser

Reputation: 16364

What hover() does is to bind a mouseenter and a mouseleave handler. What unbind() does is to remove those handlers from firing.

So your code is doing exactly what you told it to; when you click, it disables your hover handling.

Upvotes: 1

usernolongerregistered
usernolongerregistered

Reputation: 390

You can add :hover CSS to the elements like so: http://jsfiddle.net/Agony/SVkBs/2/

Upvotes: 3

Related Questions