Aaron Brewer Aaron Brewer - 6 months ago 170
HTML Question

jQuery .addClass and .fadeIn?

So, I have these h1 elements that are links and I want to add a class to them and fade that class in once the element has been hovered over, and then onMouseOut have the class removed, whilst fading the class. But using the fade function does nothing for me. Seeing as it hides the element. Any ideas?

jQuery(".categories h1 a").hover(
function () {
jQuery(this).fadeIn("slow").addClass("active");
},
function(){
jQuery(this).fadeOut("slow").removeClass("active");
});
});


Thanks!

EDIT:::

jQuery("h1").hover(function() {
jQuery(this).stop().animate({ backgroundColor: "#a7bf51"}, 800);
},function() {
jQuery(this).stop().animate({ backgroundColor: "#FFFFFF"}, 800);
});
});

Answer

Try using jQuery UI .addClass and .removeClass.

$(function() {
    $(".categories h1 a").hover(function() {
        $(this).stop(true,true).addClass("active", 500);
    }, function() {
        $(this).stop(true,true).removeClass("active", 100);
    });    
});

DEMO (For some reason, it doesn't animate properly(fade) for the first time.. but then onwards it works fine)

Edit: Updated for completeness.

You can also use .animate to get the desired effect. See below,

$(function() {
    $(".categories h1 a").hover(function() {
        $(this).stop().animate({
            backgroundColor: "#a7bf51"
        }, 800);
    }, function() {
        $(this).stop().animate({
            backgroundColor: "#FFFFFF"
        }, 800);
    });

});

DEMO