I am trying to make a JQuery script in order to change the size of some images in a portfolio. Some images are larger horizontally and some others vertically, so my idea is just to display the center part as a thumbnail. And if you click on it, you could see the real image (with an external slider ok?)
So the little script I’ve done is the following:
$(document).ready(function(){
var w_div = $('#portfolio div').width();
var h_div = $('#portfolio div').height();
$('#portfolio div a img').each(function() {
/* Correction estimate: div.width - photo.width / 2 */
var posLeft = -(w_div - $(this).width()) / 2;
var posTop = -(h_div - $(this).height()) / 2;
/* Assignment of new measures to the current image */
$(this).css({left: posLeft+'px', top: posTop+'px'});
});
});
With the loop I try to take the img group and iterate over it to calculate the correct center position. But I don’t know why it only works for the first image. I mean, this script change the css of all the images with the correct measures for the first image only. Why the assignments o posLeft and posTop doesn’t change? I don’t understand it…
(I forget to say that every image has the ‘position: relative’ sentence on the css file ok?
Thanks!
edit: Could be easier and better idea to use PHP and executing this task on the server side?
I read this too quickly. So I’m heavily editing my answer.
$(document).ready() runs as soon as the DOM is rendered. The images aren’t loaded yet and the only information the DOM has about them so far is what is in the img attributes. This is also true of the container div, which hasn’t stretched its height yet to accomodate the images. That’s probably why you get the same dimensions every time. Ideally you should manually set width and height of the images as well as the container div. If you don’t want to do that, you can use $(window).load() which will wait for all of the images to load and the DOM to be re-rendered, but this is very obvious to see.
‘left’ and ‘top’ only work on elements that are ‘position: absolute;’ and within a container with ‘position: relative;’. So the images need to be absolute and the div above them relative for left and top to work.
I’m not sure why you’re using left and top instead of width and height, since you’re trying to make a thumbnail. Another way is to calculate the maximum of the width and height and scale it down to a desired width or height.
I hope some of this clarifies enough to let you work a proper solution out.