tags:

views:

84

answers:

5

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);
              }
   });
});
A: 

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); 
              } 
   }); 
}); 
Sidharth Panwar
+1  A: 

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.

Vikash
+1  A: 

The is method returns a boolean. Use:

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

or:

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

I don't think you necessarily need the each.

$('div').click(function(){

  var img = $(this).find('img');

  if($(img).is(':visible')){
    $(img).fadeOut(700);
  }

});
Newtang
A: 

Not sure about the nesting of the divs, but since you are requesting to only fade the img I am assuming that the .star div is visible and clickable. The function below is a bit more efficient as I am using children instead of find which is recursive. Other than the selectors this should work for you.

$('div.star').click(function() {
    function () {
        $(this).children('img').fadeOut(700);
    },
    function () {
        $(this).children('img').fadeIn(700);
    }
});
Dustin Laine