Joshc
Joshc

Reputation: 3853

stop function running if selector does not exist - jquery?

I am trying to stop my autoBike(); bike function running if my #bike-main-slider div.bike data-bike attribute value does not exist.

<script>

    var bike = '<?=(isset($_REQUEST['bike']) ? htmlentities($_REQUEST['bike']) : null)?>';

    autoBike = function () {

         var bikeIndex = $('#bike-main-slider div.bike[data-bike=' + bike + ']').index();

         mainSlider.goToSlide(bikeIndex);  

    };

    autoBike();

</script>

<div id="slideshow">

     <div class="bike" data-bike="50cc"></div>
     <div class="bike" data-bike="100cc"></div>
     <div class="bike" data-bike="150cc"></div>
     <div class="bike" data-bike="200cc"></div>
     <div class="bike" data-bike="250cc"></div>
     <div class="bike" data-bike="350cc"></div>

</div>


Is this possible?

So for example if my URL is...

http://example.com/?bike=450cc

and as you can see no 450cc exists in my #slideshow divs, so is there anyway to prevent my autoBike(); function running if data-bike attribute value does not exist?

Using jQuery


Thanks

Upvotes: 0

Views: 661

Answers (3)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You can check the length of the object returned when calling the selector and if zero, simply return from the function the first thing you do.

var autobike = function () {

   var elms = $('#bike-main-slider div.bike[data-bike=' + bike + ']');
   if (elms.length === 0)
       return;

   // Do your stuff here, at least one element matched.
}

Here is a working example with the code above: http://jsfiddle.net/Gp5Xw/

length-property vs. jQuery's .size()

As calling the jQuery function with a selector will return an array, that array will have a length-property that you can read, as any other JavaScript array. Using jQuery's .size() method will produce the same result as reading the length property, but it require an additional function call, which is totally unnecessary. It's a micro-optimization to use the length-property really, but still.

From the jQuery documentation of .size():

The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

Upvotes: 2

EibergDK
EibergDK

Reputation: 564

This should work...

$(document).ready(function() {

var bike = '<?=(isset($_REQUEST['bike']) ? htmlentities($_REQUEST['bike']) : null)?>';

$('bike').each(function() {
 if ($(this).attr('data-bike') === bike) {
     autoBike();
 }
});

});

autoBike() will then only run, if your URL parameter for bike exists as an data-bike attribute...

Upvotes: 1

br3t
br3t

Reputation: 1658

autoBike = function () {
     var $bike = $('#bike-main-slider div.bike[data-bike=' + bike + ']');
     if($bike.size() > 0) {
          var bikeIndex = $bike.index();
          mainSlider.goToSlide(bikeIndex); 
     }
};

Upvotes: 1

Related Questions