views:

64

answers:

1

Is there a way to make jQuery use objects in a conditional statement as an object in a hierarchy. For Example, I want to validate that something exist then tell it to do something just using the this selector.

Like this

if ($(".tnImg").length) {

//i have to declare what object I am targeting here to get this to work

            $(this).animate({
            opacity: 0.5,   
            }, 200 );
  }

Is there a way to get jQuery to do this? I guess theres not a huge benefit but i still am curious

+2  A: 

In jQuery, if nothing is found, then nothing happens, for example:

$(".tnImg").animate({ opacity: 0.5 }, 200 );

This won't error, if it doesn't find anything with class="tnImg" it simply won't run on any elements. This is one of the fundamentals that makes jQuery so terse :)

If you wanted to do lots with the object, this would let you use it as $(this) for each one:

$(".tnImg").each(function() {
  //$(this) is the current class="tnImg" element, this code runs for each one
  $(this).animate({ opacity: 0.5 }, 200 );
});
Nick Craver
ok so your saying i can use the each function rather the finding out if it exist. and the code will still work. Then I can use the hierarchy. Now let say if I have more parameters to the animate function plus multiple events with different animations to each event.If i use the each function will it bypass the code inside the callback rather then running the code even when the element is not there.
Jacob Lowe
@Jacob - Can you post an example of what you *want* to do? It's often easier to just illustrate how to do an example :) If you call an animation, the callback runs for **each** element that was animated (they all animate individually). If the selector found no elements, then none are animated and the callback wouldn't run even once, make sense?
Nick Craver
makes perfect sense thank you so much you are a giant help.
Jacob Lowe
@Jacob - No problem, that's what SO is for, is you have more questions feel free, I'll answer if I can.
Nick Craver