RCNeil
RCNeil

Reputation: 8769

JQuery function after addClass() on class added

$('#closecallout').click(function() {
    $('.callout').animate({"right" : "-260px"}, 500).addClass('calloutclosed');
});
$('.calloutclosed').hover(function() {
    $(this).animate({"right" : "0px"}, 500);
}, function() {
    $(this).animate({"right" : "-260px"}, 500);
});

The click function is meant to 'hide' the callout box, and then afterwards, when hovered, it will move back into focus.

Why does the hover function not work? Is it because these are both within a jQuery(function($){ }); ?

What steps should I take to rectify this?

http://jsfiddle.net/R5Dmu/

Many thanks SO

Upvotes: 1

Views: 2851

Answers (2)

Musa
Musa

Reputation: 97707

To get events to trigger on elements based on their current class you'll need to use event delegation with .on().

$('#closecallout').click(function() {
    $('.callout').animate({"right" : "-260px"}, 500).addClass('calloutclosed');
});
$(document).on('mouseover', '.calloutclosed', function() {
    $(this).animate({"right" : "0px"}, 500);
}).on('mouseout', '.calloutclosed', function() {
    $(this).animate({"right" : "-260px"}, 500);
});

DEMO

Upvotes: 5

Norbert Pisz
Norbert Pisz

Reputation: 3440

When You call click function You need to add class and implement hover function. In your code You added class on click event but not implement hover function. You implement hover function on document ready and then Jquery could find selector with calloutclosed class becouse is not click event yet.

Check this:

jQuery(function ($) {

//CALLOUT
$('#closecallout').click(function () {
    $('.callout').animate({
        "right": "-260px"
    }, 500)
    $('.callout').addClass('calloutclosed');

    $('.calloutclosed').hover(function () {
        $(this).animate({
            "right": "0px"
        }, 500);
    }, function () {
        $(this).animate({
            "right": "-260px"
        }, 500);
    });

});
});

Upvotes: 2

Related Questions