Tuesday, February 14, 2012

getting the image width from the href tag instead from img tag


i am working on a project in which i require the width of a image from href when i click on the specific image the width if the image displays in a alert .



the following is the href and image code i am using




<li>
<a href="<?php echo $pic;?>?id=<?php echo $id;?>&pic=<?php echo $picID;?>" data-title="" data-desc=" " data-rel="group2" data-bw="<?php echo $pic;?>" class="lightbox" id="plzx" >
<img src="<?php echo $pic;?>" width="160" height="160" title="Click To View"/></a>
</li>



whenever i try to get the width of the image it takes the image width from the img tag not from the href . as the img tag width is already defined "160" . is there a way possible for getting the width of the image from the <a href



i am using the following code which is nit working




$('a').click(function() {
var image = $("<img />").attr("src", $(".lightbox").attr("href"));
$(document).append(image);
alert(image.height());
alert(image.width());
image.remove();
});



the html code




<li>
<a href="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg?id=3&pic=101" data-title="" data-desc=" " data-rel="group2" data-bw="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg" class="lightbox" id="plzx" >

<img src="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg" width="160" height="160" title="Click To View"/></a>

</li>

1 comment:

  1. Based on something like:

    <a href="/path/to/big.jpg"><img src="/path/to/small.jpg"></a>


    This should do it:

    $('a').click(function() {
    $(new Image()).load(function() {
    alert(this.width); // image width
    alert(this.height); // image height
    }).attr('src', this.href);
    });


    Update: If you need to continue your program using the width/height, try:

    var width,height;
    $('a').click(function() {
    $(new Image()).load(function() {
    width = this.width;
    height = this.height,
    onLoaded();
    }).attr('src', this.href);
    });
    function onLoaded() {
    alert(width);
    alert(height);
    // continue...
    }


    You don’t need to append the temporary image to the document, but you do need to add a load listener before you extract width/height.

    Remember that the AdBlock extension can affect the outcome of the extraction in webkit, so please turn it off when debugging.

    ReplyDelete