Hep with Javascript to automagically resize post images. - Postet den (3061 Views)
Senior Member
bobby131313
Innlegg: 1163
1163
Here is the javascript used....
Code:
$(window).load(function() {

$('img').each(function() {
var ratio = 2.0; // Used for aspect ratio
var maxWidth = parseInt($(window).width() / ratio); // Max width for the image
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", parseInt(height * ratio)); // Scale height based on ratio
//$(this).css("border", "2px dashed #890000"); // Scale height based on ratio
$(this).css("cursor", "pointer"); // Scale height based on ratio
//$(this).attr("title", "Click to see if there is a larger version!.");
}
});
});

It works but sometimes it takes a bit to fire so the browser has horizontal scrollbars. When the js kicks in sometimes the browser will snap back and sometimes it wont. Seems hit or miss with all browsers.
I tried putting max-width:90% on my image class but then the js grabs the css adjusted width so it doesn't resize any images.
So the $64 question is, is there any way to tweak this js to force it to grab the native width instead of the CSS adjusted width? That should solve the problem.
I've googled and played with this off and on for days with no luck.
   
 Sidestørrelse 
Postet den
Forum Moderator
huwtest
Innlegg: 30
30
try this

var width = $(this)[0].naturalWidth;
var height = $(this)[0].naturalHeight;
Postet den
Senior Member
bobby131313
Innlegg: 1163
1163
That gets me closer, thank you! Now the CSS part of it is intermittent, I'll play with it some more today.
Postet den
Senior Member
bobby131313
Innlegg: 1163
1163
Ok I got this working but I have one more question.
Any way to get this to only affect images inside a certain CSS class? Or inside a CSS ID?
It's affecting my header logo, don't ever remember it doing that before but it is now.
Postet den
Forum Admin
HuwR
Innlegg: 20611
20611
in jquery something like this should work

$('img').not('.myclass').each or something along those lines
Postet den
Senior Member
bobby131313
Innlegg: 1163
1163
Played with that for a bit with no luck.
How about this, would it be simpler to check if it's a PNG image and not resize it if it is?
Postet den
Forum Admin
HuwR
Innlegg: 20611
20611
javascript won't know if it is a png or not, not sure why .not isn't working, it should.
in your initial post where you use $('img').each(function() {
using $('img').not('.someclass').each(function() { should work how you want.
 
Du må legge inn en melding