I have a few elements. The number of them on the page changes constantly, keep that in mind.
The element is called .portalimg. I need to say if the width > height, set it’s width to 125px. If the height > width, set the height to 125px.
Here’s what I have:
$('.portalimg').each(function() {
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
EDIT: It alerts success but doesn’t apply the width & height.
Where did I go wrong?
EDIT 2: Updated code with cleanest from below. That still only constrains the height property, even if the images is taller then it is wide. Take a look:
http://jacksongariety.com/gundoglabs/
EDIT 3: The issue is they all return 0. If I have an alert say the value of pimgw or pimgh, it’s always 0.
EDIT 4: Finally got the best, cleanest code possible with caching and it’ll always load correctly, even if it draws images form the cache:
$(function(){
$('.portalimg').ready(function(){
$('.portalimg').fadeTo(0,1).each(function(index) {
var a = $(this);
if (img.width() > a.height()) {
a.css('width','135px')
} else {
a.css('height','125px')
}
});
});
});
If there are multiple elements of class portalimg you could simply use a .each iterator: http://api.jquery.com/each/