If this = first <li> with class "xyz", then execute the function
I have a <ul> with 6 elements. Each item has a class of planning, landscape, or environment. Elements are part of the jQuery Cycle slide show on the page. What I'm going to do is show something on the page if the displayed list item is the first item with a specific class.
As you can see below, I have two list items with a planning class. How do I determine if the displayed list item is displayed first with the planning class?
The loop gives me a big little function to help me, I'm just not sure how to write if() inside my helper function to call the element that I want to display on the page.
Any help is much appreciated!
** Edit ** Here is jsFiddle: jsfiddle.net/73y2R/1
Here's the html:
<ul> <li class="planning"> <img src="images/pl_slide1.jpg"> <h2>Headline</h2> <p>Lorem Ipsum</p> </li> <li class="planning"> <img src="images/pl_slide1.jpg"> <h2>Headline</h2> <p>Lorem Ipsum</p> </li> <li class="landscape"> <img src="images/la_slide2.jpg"> <h2>Headline</h2> <p>Lorem Ipsum</p> </li> <li class="landscape"> <img src="images/la_slide2.jpg"> <h2>Headline</h2> <p>Lorem Ipsum</p> </li> <li class="environmental"> <img src="images/en_slide1.jpg"> <h2>Headline</h2> <p>Lorem Ipsum</p> </li> <li class="environmental"> <img src="images/en_slide1.jpg"> <h2>Headline</h2> <p>Lorem Ipsum</p> </li> </ul> And helper function:
function onBefore() { var theid = $(this).attr('class'); $('#services h4').removeClass('recolor'); $('#slideShow ul li').removeClass('showTitle'); if($(this).hasClass('planning')){ $('#arrow').animate({'paddingLeft':'60px'}); $('#' + theid).addClass('recolor'); } else if ($(this).hasClass('landscape')){ $('#arrow').animate({'paddingLeft':'330px'}); $('#' + theid).addClass('recolor'); } else if ($(this).hasClass('environmental')){ $('#arrow').animate({'paddingLeft':'598px'}); $('#' + theid).addClass('recolor'); } } Not sure why the first version does not work (there may be problems with jQuery extension pseudo-classes with the ??? method).
Use $(this).is($("li.planning:first")) instead of $(this).is("li.planning:first") (we pass the jQuery object to the is method instead of the row selector)
Try the following:
if($(this).is($("li.planning:first"))){ //This is the first li... } Check out this jsFiddle: http://jsfiddle.net/73y2R/2/
Hope this helps:
DEMO: http://jsfiddle.net/oscarj24/hwzyx/1/
JQuery
$(document).ready(function(){ var firstClass = $("ul li:first-child").attr('class'); var isPlanning; ($.trim(firstClass) == 'planning') ? isPlanning = true : isPlanning = false; var isLandscape; ($.trim(firstClass) == 'landscape') ? isLandscape = true : isLandscape = false; var isEnvironmental; ($.trim(firstClass) == 'environmental') ? isEnvironmental = true : isEnvironmental = false; if(isPlanning) alert('First child class is planning'); if(isLandscape) alert('First child class is landscape'); if(isEnvironmental) alert('First child class is environmental'); }); Respectfully:-)