4

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?

1 Answer 1

8

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);
        }
    }
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but the class needed to be added to the div, not the image. So I added parent() to it. :)
@Constant M - I missed that - I edited that in right before you posted, oh well you get the idea anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.