tags:

views:

7178

answers:

6

In jQuery I need to do an if statement to see if $this doesn't contain the class '.selected'.

$(".thumbs").hover(function(){

$(this).stop().fadeTo("normal", 1.0);
},function(){
$(this).stop().fadeTo("slow", 0.3);

});

Basically when this function is run (on hover) I don't want to perform the fades if the class '.selected' has been appended to the div, this will mean that the image will be at full opacity to signify that it's selected. Searched on Google to no luck even though it's a simple question of how to use an IF statement...

+20  A: 

Use the "not" selector.

For example, instead of:

$(".thumbs").hover()

try:

$(".thumbs:not(.selected)").hover()

alphadogg
Six of one, half a dozen of the other... :)
alphadogg
thinking about it, if the OP is adding the class to the div at some point after document.ready then I don't think your syntax will work
Russ Cam
Plus there are multiple div's called .thumbs....
zuk1
@zuk1: Well, from your snippet, you take all elements with class 'thumb' and do a hover() on each one. Are you saying you want to just do hover on one element? WHat is that one element? I am confused.
alphadogg
@Russ: Correct. If you use the above, then it will take all elems currently in the DOM at the time it is executed, and to those with class 'thumb' and not 'selected' it will do hover().
alphadogg
+5  A: 

jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

if (!($(this).hasClass("selected"))

Take a look at my example of use

  • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
  • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
  • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

Here is the code for it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"&gt;&lt;/script&gt;
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>


<!-- jQuery code here -->
<script type="text/javascript">
$(function() {

$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});

$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );

$('.thumbs').hover(fadeItIn, fadeItOut);


});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}
</script>


</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>

EDIT:

this is just a guess, but are you trying to achieve something like this?

  • Both divs start at 30% opacity
  • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
  • Clicking a div adds/removes the 'selected' class

jQuery Code is here-

$(function() {

$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);

});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}

<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>
Russ Cam
doesn't work for some reason :($(".thumbs").hover(function(){if (!($(this).hasClass(".selected")){$(this).stop().fadeTo("normal", 1.0);},function(){$(this).stop().fadeTo("slow", 0.3);}});and it breaks my entire code, none of the JS works with that added
zuk1
does hasClass require the .? hasClass('selected') instead of hasClass('.selected')
bendewey
Russ' example may work if you use "selected" instead of ".selected"?
alphadogg
apologies, didn't mean to put the . in there. Updated now
Russ Cam
I've added some examples to my answer, to show the code working
Russ Cam
A: 

You can also use the addClass and removeClass methods to toggle between items such as tabs.

e.g.

if($(element).hasClass("selected"))
   $(element).removeClass("selected");
Tawani
why not just use toggleClass()?
Russ Cam
Because the element might have other classes.
Tawani
A: 

How about instead of using an if inside the event, you unbind the event when the select class is applied? I'm guessing you add the class inside your code somewhere, so unbinding the event there would look like this:

$(element).addClass( 'selected' ).unbind( 'hover' );

The only downside is that if you ever remove the selected class from the element, you have to subscribe it to the hover event again.

Juan
+1  A: 
$(".thumbs").hover(
    function(){
        if (!$(this).hasClass("selected")) {
            $(this).stop().fadeTo("normal", 1.0);
        }
    },
    function(){
        if (!$(this).hasClass("selected")) {
            $(this).stop().fadeTo("slow", 0.3); 
        }   
    }
);

Putting an if inside of each part of the hover will allow you to change the select class dynamically and the hover will still work.

$(".thumbs").click(function() {
    $(".thumbs").each(function () {
        if ($(this).hasClass("selected")) {
            $(this).removeClass("selected");
            $(this).hover();
        }
    });     
    $(this).addClass("selected");       
});

As an example I've also attached a click handler to switch the selected class to the clicked item. Then I fire the hover event on the previous item to make it fade out.

Jeff Adams
A: 

I have something like this - but for some reason it doesn't work - any ideas? Basically what I'm trying to do is - when the page loads and the button is already active, then after the mouse goes off the button - it would stay active as before - all other buttons will loose the "act" class if they didn't have it before the hover.

if($("#mnv ul").length > 0) {       
    $("#mnv ul").hide();        
    $("#mnv li").hover(function() {     
        var active = $(this).hasClass("act");
        $(this).addClass("act");
        $(this).find("ul").stop(true, true).fadeIn("fast");     
    }, function() {
        $(this).removeClass("act");
        $(this).find("ul").stop(true, true).fadeOut("fast");
    }); 

}
Seb