This code is supposed to reposition gallery images inside of their square div boxes. All the images have a set height e.g. 100px. But their widths are different. Rather than only show the left-most 100px of every picture, I'd rather it show the center.
All I need is to go through each img and change the left property to shift the images left.
$('img.gall_imgs').load(function() {
var $imgWidth = parseInt($(this).width); // "$(this)" or "this"? parseInt() needed?
var $divWidth = parseInt($(this).closest('div').width);
if($imgWidth > $divWidth) { // if img is wider than its containing div, we'll shift it left
var $position = -1 * ($imgWidth/2 - $divWidth/2); // will give decimals?
$position = parseInt($position) + "px"; // make $position format "123px". parseInt() needed here?
// var $position = '-50px'; // tested with pre-set position
this.css("left", $position); // "$(this)" or "this"?
}
//}
});
Also, I don't even know how to test variables values inside of jquery. I tried putting in an alert($imgWidth) but it obviously didn't work.
EDIT: Here is the CSS and HTML I have now:
.gall_thumb_img { // the div surrounding the img
width:200px;
height:200px;
margin-left:auto;
margin-right:auto;
overflow:hidden;
text-align:center; // just added this per suggestions. No effect
}
.gall_thumb_img img{ // the img
position:absolute;
display:block;
height:200px;
min-width:200px;
}
HTML:
<div id="gall_box">
<div class="gall_thumb_box" id="gall_thumb_box_0" >
<div class="gall_thumb_img" id="gall_thumb_img_0" >
<a href="?c=ecards&v=single&idx=23&img_dir=nature">
<img class="gall_img" id="img0" src="http://example.com/small.jpg?20111211044810"></a>
</div>
</div>
</div>
EDIT2: Here is what I've changed the jquery to based on various suggestions. Still no change in end result.
$(window).load(function() {
$('img.gall_imgs').each(function() {
var imgWidth = $(this).width(); // "$(this)" or "this"?
var divWidth = $(this).closest('div').width();
alert(imgWidth);
if(imgWidth > divWidth) {
var position = -1 * (imgWidth/2 - divWidth/2); // will give decimals?
position = position + "px"; // make position format "123px".
// var position = '-50px'; // tested with set position
this.css("left", position); // "$(this)" or "this"?
}
});
});
Text-align center is a good idea that I will use if I can get it to work, but I would still like to know why my jquery code is not working. Thank you.