Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hover callback function problem

I'm trying to get an image to stay opaque when clicked on, along with a fade in/out function on hover. When clicked it will remove one class and add a 'selected' class to the element. Problem is that altough the original class is removed, the callback still executes as if the class is still in the element. Thus, if you click on it, it changes the opacity to 1 and removes the .gallery_item class, but still fades out the element on hover off. I know the code could be improved, but it's just for demonstration purposes.

The hover code:

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

Code for the click/make the element opacity 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 it a better way to accomplish this?

like image 261
Constant Meiring Avatar asked Feb 28 '23 03:02

Constant Meiring


1 Answers

Try checking if the image has the selected class before applying the fade effect within 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);
        }
    }
);
like image 103
karim79 Avatar answered Mar 08 '23 13:03

karim79