Daniel Daniel - 1 year ago 59
jQuery Question

jQuery: how to allign image in the middle of a div using each function

I have created a script in order to center in the middle all images in a div using the each function. This is the code:


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

var colHeight = $(this).innerHeight();
var colWidth = $(this).width();



var getCenter = (colHeight - imgHeight);
var toBeCentered = (getCenter / 2);

var toReduceWidth = (colWidth - imgWidth);
var getReducedWidth = (toReduceWidth / 2);



$('.myImg').css({'top': toBeCentered + 'px','left': 0});


});


With the var called toBeCentered I get the height of all divs


$('.myImg').css({'top': toBeCentered + 'px','left': 0});


The piece of code above displays always the last one .col div height and not all beginning from the very first.
How can I set the related div height to the images?

Answer Source

You have to do something like:

$('.column').each(function (){
    // ...
    $(this).find('.myImg').css({'top': toBeCentered + 'px','left': 0});

});

Because you are setting css attributes for all .myImg objects in every iteration of each function. Above solution will work if .myImg objects are in .column class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download