views:

48

answers:

4

Hello,

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

+1  A: 

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

Paul
assuming <a href=""><img src=""></a>
Jean
Ah, ok, then you need to use a parent selector to get the anchor. Could you elaborate on the application? Is the inner image a thumbnail or the full thing? If you are loading the image for the first time, you will need to wait until the image loads to know the width/height for example...
Paul
hmm...how do I trigger height after page load and I want to get the anchor too
Jean
Not sure what you're asking...but the javascript image object has an onload event you can set to be called once the image loads. To get the anchor tag you could use $('A:has(img:regex(data:extension, jpg))'). (I assume you are using James Padolsey's regex filter.)
Paul
+1  A: 
$('img').each(function() {
   var imgwidth  = $(this)[0].offsetWidth;
   var imgheight = $(this)[0].offsetHeight;
    console.log(imgwidth ,' X ' , imgheight);
});

I think this should help

Ninja Dude
Does not work.....
Jean
A: 

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.

Rei Miyasaka
A: 

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.

BalusC