Binding click function on each div JQuery

24,909

Solution 1

The is method returns a boolean. Use:

if($(this).find('img').is(':visible'))

or:

if($(this).find('img:visible').length)

Solution 2

Try this:

$('div').each(function(){ 
   $(this).click(function(){ 
          if($(this).find('img').is(':visible')){ 
                    $(this).find('img').fadeOut(700); 
          } 
          else{ 
                    $(this).find('img').fadeIn(700); 
              } 
   }); 
}); 

Solution 3

Unlike the other filtering and traversal methods, .is() does not create a new jQuery object. Instead, it allows us to test the contents of a jQuery object without modification.

So, you can not use length on it as it returns a boolean value. Remove 'length' and it should work.

Share:
24,909
Felix
Author by

Felix

Love to draw ideas in paper and make it real.

Updated on September 08, 2020

Comments

  • Felix
    Felix almost 4 years

    I need to bind the click function on each div of this ordered list in order to make hide/show an image on each imgXX div, I'm newbie with JQuery

    <ol id='selectable'>
     <li class="ui-state-default">
       <div id="img01" class="img">
          <div id="star01" class="star">
              <img src="../ima/star.png" height="30px"/>
          </div>
       </div>
     </li>
     <li class="ui-state-default">
       <div id="img02" class="img">
          <div id="star02" class="star">
              <img src="../ima/star.png" height="30px"/>
          </div>
       </div>
     </li>
    </ol>
    

    JQuery

    $('div').each(function(){
       $(this).click(function(){
              if($(this).find('img').is(':visible').length){
                        $(this).find('img').fadeOut(700);
              }
              else{
                        $(this).find('img').fadeIn(700);
                  }
       });
    });
    
    • Sidharth Panwar
      Sidharth Panwar almost 14 years
      So what is giving you grief? Umm... ($(this).find('img').is(':visible').length is not correct, I think. is() gives you a true false. Applying length to it might be weird.
    • user3167101
      user3167101 almost 14 years
      @Sidhart You are right, it should be find('img:visible')
    • Guffa
      Guffa almost 14 years
      Note that you are binding the click event on the nested div elements, so they might fire twice. You may want to use $('div.img') or $('div.star') to single out one set of div elements. Also, .each(function(){ $(this).click(...); }) can be shortened to just .click(...) as it applies the event to all elements in the collection.