views:

293

answers:

4

With jQuery, i change the src of an image on click

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

 $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg');
 $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg');

The problem is, that the NEW image width is different that the old. HOW do i get the NATIVE width of the new image (like the little arrow that get that in dreamweaver

+1  A: 

Did the old image have a width and height set to it? If you use $(image).width("") it should reset the width back to what it was before you applied any width changes to it (similarly for height). I don't think this will work for images that had their width set via CSS or the property though. After you reset to the old width, you can use .outerWidth() to get the width of the image.

Willson Haw
+1  A: 

You want to get the real width of the image before changing it, then set the new picture to that width. you can do this with $(img).load:

var pic_real_width;
var pic_real_height;

$(img).load(function() {
    // need to remove these in of case img-element has set width and height
    $(this).removeAttr("width")
           .removeAttr("height");

    pic_real_width = this.width;
    pic_real_height = this.height;
});

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

        $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg').width(pic_real_width);
        $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg').width(pic_real_width);
GSto
will try it, right now, look good !
marc-andre menard
+1  A: 

This is the plain javascript way to do it. It should be easy to integrate this into your code.

var newimage = new Image();
newimage.src = 'retouche-hr' + newlinkimage + '-a.jpg'; // path to image
var width = newimage.width;
var height = newimage.height;
Scott Saunders
width always return 0
marc-andre menard
make sure the image path is a valid image path to an actual image
Scott Saunders
The image must be already loaded when you call for the height/width. The second line loads the image, but it may not be finished loading by the 3rd or 4th line runs.
Scott Saunders
the problem is exacly that the image is not load.... i have open another question and got the answer : http://stackoverflow.com/questions/1645166/image-naturalwidth-return-zero
marc-andre menard
A: 

this code always return Zero '0'

 var newimage = new Image();
 newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
 var width = newimage.naturalWidth;
 var height = newimage.naturalHeight;
 alert (width);

WHY ???

marc-andre menard