Kamalakannan Kamalakannan - 1 month ago 19
jQuery Question

Add Class on ready, remove class on hover

I'm creating my portfolio website. I'm looking to add class on document ready, and remove/change that class to a different class on hover.
I'm using lightgallery & CSS gram filters to my images on load and hover.

$(document).ready(function() {
$("#gallery li a").load(function(){
$($(this).find("img")[0]).addClass("inkwell");
});
$("#gallery li a").hover(function(){
$($(this).find("img")[0]).removeClass("inkwell").addClass("mayfair");
}); });


the jQuery code above didn't seem to work well.

Please help, Thanks.

Answer

An anchor doesn't load, it's just there from the start and has no external resource to load, so there's no onload handler

$(document).ready(function() {
    $("#gallery li a img").addClass("inkwell");

    $("#gallery li a").on({
      mouseenter : function() {
        $(this).find("img").removeClass("inkwell").addClass("mayfair");
      },
      mouseleave : function() {
        $(this).find("img").removeClass("mayfair").addClass("inkwell");
      }
    }); 
});

CodePen

Comments