views:

129

answers:

2

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?

+4  A: 

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);
        }
    }
);
karim79
Thanks, but the class needed to be added to the div, not the image. So I added parent() to it. :)
Constant M
@Constant M - I missed that - I edited that in right before you posted, oh well you get the idea anyway.
karim79
A: 

So this was the solution:

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

Thanks karim79!

Constant M