views:

100

answers:

2

Hi, I am trying to write a simple if statement in javascript (jquery library) that simply finds the div.video element in the page and if it can find it set the variable 'arrows' to true, if it can't to false.

Here is what I have so far:

jQuery(document).ready(function () {
    // Hiding of prev & next arrows on movie pages.
 var arrows = false;

 if (jQuery('body').find('div.video'))
 {
  arrows = false;
 } else {
  arrows = true;
 }

 if (
  arrows == true
 ){
  jQuery('a.prev').show();
  jQuery('a.next').show();
 } else {
  jQuery('a.prev').hide();
  jQuery('a.next').hide();
 }

});

The page I am using it on is currently under development but here is the dev links: The first one is a sample page with a div.video element so the arrows should be hidden:

video element page

This second link does not include a div.video item, instead it has a div.photo element. Since div.video is not on the page it should show the arrows here.

photo element page

Weird thing is, the if statements does hide the arrows but it does so on all pages not just the ones with video content.

Any help would be much appreciated as Firebug doesn't seem to register any kind of errors in my js.

Thanks for reading, Jannis

+2  A: 

jQuery returns an empty list when it can't find any elements, so your statement always works out to be true.

Try:

if(jQuery("div.video").length > 0){
  arrows = false;
} ....
Mike Robinson
Thank you very much. This works perfectly.Just learned something new about JS :)Thanks
Jannis
The " > 0" is not needed.
J-P
Sweet. Thanks for the comment J-P, removed the > 0 and still works as it should. Thanks
Jannis
Indeed - and now my handicap is lowered in code golf
Mike Robinson
+1  A: 

The size() function can help you to gauge the count of the elements matched by a selector. Also, it is not necessary to wrap the body element in order to select its elements.

For example:

$(document).ready
(
  function()
  {
    var arrows = $("div.video").size() === 0;
    if(arrows)
    {
      $("a.prev, a.next").show();
    }
    else
    {
      $("a.prev, a.next").hide();
    } 
  }
);
David Andres
Thank you for your solution and taking the time to read my post.
Jannis