Execute function for each class you find

6

I'm creating a picture gallery within thumbnails by automatically setting them where I use the calculation below:

if($('.thumb img').width()<$('.thumb img').height()){//portrait

  $('.thumb img').css({
    maxWidth:'100%'
  });
  $('.thumb img').css({
    marginTop:-(($('.thumb img').height()-$('.thumb').height())/2)
  });
}else{//landscape
  $('.thumb img').css({
    maxHeight:'100%'
  });
  $('.thumb img').css({
    marginLeft:-(($('.thumb img').width()-$('.thumb').width())/2)
  });
}

If I have an image, it calculates well, but when I have images of different sizes it encounters a bug . I want to know if there is a way I can execute this function every time I find a div with class .thumb , so I can treat image by image and structure them within their specific div's.     

asked by anonymous 16.12.2013 / 17:45

3 answers

5

To execute a function for each element, you use:

$('.thumb img').each(function(){
if($(this).width()<$(this).height()){//portrait

 $(this).css({
    maxWidth:'100%'
  });
  $(this).css({
    marginTop:-(($(this).height()-$('.thumb').height())/2)
  });
}else{//landscape
  $(this).css({
    maxHeight:'100%'
  });
  $(this).css({
    marginLeft:-(($(this).width()-$('.thumb').width())/2)
  });
}
});

Note that within the each method, all references to class .thumb and element img have been changed by $(this) , in which case this points to the element that is being traversed.

    
16.12.2013 / 17:51
3

You need a loop:

$('.thumb img').each(function(){
    var img = $(this);
    var proporcao = img.width() / img.height();

    // Retrato
    if(proporcao > 1) {
        img.css({
            maxWidth:'100%',
            marginTop:-((img.height()-img.closest('.thumb').height())/2)
        });

    // Paisagem
    } else {
        img.css({
            maxHeight:'100%',
            marginLeft:-((img.width()-img.closest('.thumb').width())/2)
        });
    }
});
    
16.12.2013 / 17:49
3

A jQuery function for this purpose is .each () that allows you to execute a block of code for each element found:

$('.thumb').each(function() {

   // o teu código aqui
});
    
16.12.2013 / 17:50