javascriptjqueryjquery-eventsmouseenter

Jquery class change hover over effect


Is there a better way to do the following?:

$('.favorite').mouseenter(function(){
    var el = $(this);
    if(el.hasClass('fa-star-o')) {
        el.removeClass('fa-star-o');
        el.addClass('fa-star');

        el.mouseleave(function(){
            el.removeClass('fa-star');
            el.addClass('fa-star-o').unbind('mouseleave');
        })
    }
})

It's for a simple hover over effect using font-awesome classes.


Solution

  • I think the cleanest way is to use jquery functions hover() and toggleClass() :

    $('.favorite').hover(function(){
         $(this).toggleClass("fa-star fa-star-o"); 
    });