Problem with jQuery callback function

I am trying to get an image that will remain opaque when clicked, along with the fade in / out function when it hangs. When clicked, it will remove one class and add to the 'selected' element. The problem is that if the original class is deleted, the callback is still executed as if the class is still in the element. Thus, if you click on it, it will change the opacity to 1 and delete the .gallery_item class, but the element will fade on hover anyway. I know that the code can be improved, but it is just for demo purposes.

Guidance Code:

$(".gallery_item img").hover( function () { $(this).fadeTo('50', 1); }, function () { $(this).fadeTo('50', 0.6); } ); 

Code for click / make opacity of element 1:

 $(".gallery_item img").click(function() { $('.gallery_item').removeClass('gallery_item_selected'); $(this).parent().addClass('gallery_item_selected').removeClass('gallery_item'); $(this).css("opacity", "1"); }); 

What am I doing wrong / what is the best way to do this?

+4
source share
1 answer

Try checking if the image has the selected class before applying the fade effect in the mouseout function:

 $(".gallery_item img").hover( function () { $(this).fadeTo('50', 1); }, function () { if(!$(this).parent().hasClass('gallery_item_selected')) { $(this).fadeTo('50', 0.6); } } ); 
+8
source

All Articles