Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding click function on each div JQuery

Tags:

jquery

each

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);
              }
   });
});
like image 906
Felix Avatar asked Sep 08 '10 05:09

Felix


2 Answers

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); 
              } 
   }); 
}); 
like image 164
Sidharth Panwar Avatar answered Sep 17 '22 22:09

Sidharth Panwar


The is method returns a boolean. Use:

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

or:

if($(this).find('img:visible').length)
like image 22
Guffa Avatar answered Sep 19 '22 22:09

Guffa