Tutorial :Get href,src,width,height of image using jQuery



Question:

I want to get the href, src, width, height of all images on a page. The jQuery code is

$('img:regex(data:extension, jpg)').each(function() {      var imgsrc = $(this).attr('href');     //$(this).attr('width') =0;                                         var newImg = new Image();  newImg.src = imgsrc;      var width = newImg.width;  //width is 0;      });  

Not sure what is wrong, any ideas?

Thanks Jean


Solution:1

Well IMG tags use 'src' not 'href'.


Solution:2

This example works for your problem.

$("img").each(function(){      alert($(this).attr('src') + " - " + $(this).attr('width') + " - " + $(this).attr('height'));  });  


Solution:3

I wouldn't be surprised if this doesn't work -- at least, not until the document and all of its resources are completely loaded. HTML doesn't normally specify the width or height of an image unless it's been specified in the tag itself.

So you'd have to at least wait for the onload event.

The other solution, which could prove to be a bit of a pain, is to check the rendered width/height of the image on the server side and provide that in the <img width, height> attributes.


Solution:4

Assuming that you have this markup:

<a href="link1"><img src="foo.jpg"></a>  <a href="link2"><img src="bar.jpg"></a>  

You can obtain the wrapping link by jQuery.closest() as follows:

$('img[src$=.jpg]').each(function() {      $img = $(this);      $link = $img.closest('a');      var href = $link.attr('href');      // ...        // Assuming you want the image's client width/height:      var width = $img.width();      var height = $img.height();      // ...  });  

The [name$=value] is by the way the attribute-ends-with selector.


Solution:5

$('img').each(function() {     var imgwidth  = $(this)[0].offsetWidth;     var imgheight = $(this)[0].offsetHeight;      console.log(imgwidth ,' X ' , imgheight);  });  

I think this should help


Solution:6

In regards to the above answer from Rei...that's correct, you really want to be sure everything has completely loaded first before you start grabbing dimensions. A helpful tool for this is jquery.imagesloaded .


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »