Ray
Ray

Reputation: 3060

jquery apply opacity only if element not a particular class

I'm trying to build a number of graphics, initialize them with 0.5 opacity and when hovered over or clicked the opacity is changed to 1. (it's part of an article selection element of a page - sort of tab like but not tabs) I can do the hover over bit but adding code to handle the clicked part is I think being over ridden by the hover event when the mouse moves away from the element. If I add a class to the element that has been clicked to say "selected" is there a way I can apply the hover element only if not class="selected".

Here's my scrappy code!

$(document).ready(function() {

        $('.pic').stop().animate({ opacity: 0.5 }, 250);

        $('.pic').each(function() {
            $(this).hover(function() {
                $(this).stop().animate({ opacity: 1.0 }, 250);
            },
           function() {
               $(this).stop().animate({ opacity: 0.5 }, 250);
           });

           $(this).click(function() {
               alert('Clicked');
               $('.pic').stop().animate({ opacity: 0.5 }, 250);
               $(this).stop().animate({ opacity: 1.0 }, 250);
           });

        });
    });

Is there a better (cleaner) way to do this?

I tried CSS and using Jquery to change the css class but couldn't quite get it to work so back to this.

Thank you

Upvotes: 0

Views: 241

Answers (1)

Gabe
Gabe

Reputation: 50493

Check if the element in question hasClass() and do something if it doesn't...

Example:

if(!$(this).hasClass('selected')){  
  // do stuff
}

Upvotes: 1

Related Questions