Igor Martins
Igor Martins

Reputation: 2047

Change image src if the width is larger then original image

I have an application that defines the width of an image through html like this:

                                                                   ↓↓↓↓↓↓↓↓↓↓↓↓
<img id="teste" class="item" src="../img/fotos/4medium.jpg" style="width: 430px; display: block; margin-top: -7px; margin-left: 0px; max-width: 9999em; height: auto;"/>`

But, if the width of the image is less than 430px, the app expands the image possibly warping or pixelating it.

Is there a way to check if the style="width" is bigger than the original picture width and, if so, change the src to another image?

I think that it should look something like this:

if ($('#teste').width() > $(4medium.jpg).width()) {
$('img').attr('src', '../img/fotos/4larger.jpg');
} else {
$('img').attr('src', '../img/fotos/4medium.jpg');
}

Thanks in advance.

Upvotes: 0

Views: 345

Answers (2)

Runthral
Runthral

Reputation: 432

Ideally this is something you would check with a script on the server (since otherwise you potentially will have to download both images to the client). Something like this should work:

var testImg = new Image();
testImg.src = '../img/fotos/4medium.jpg';
testImg.onLoad = check_image_size( testImg );

Then test the width to see if you need to load the larger image:

function check_image_size( obj ) {
  var url = obj.src;
  if ( obj.width > 430 )
     url = '../img/fotos/4larger.jpg';
  $('#teste').attr( 'src', url );
}      

This is an ugly approach (and potentially slow because it potentially could load both images), but I'm not sure if there is a more elegant way to do it client side.

Upvotes: 2

isJustMe
isJustMe

Reputation: 5470

Try:

var teste_img = document.getElementById('teste'); 
var teste_width = teste_img.clientWidth;
var medium_img = document.getElementById('medium'); 
var medium_width = teste_img.clientWidth;


if(test_width > medium_width ){
    $('img').attr('src', '../img/fotos/4larger.jpg');
}else{
    $('img').attr('src', '../img/fotos/4medium.jpg');
}

Upvotes: 0

Related Questions