views:

72

answers:

4

Hi there,

I have written code like this. <img id='test_img' src='../../..' />

I want to get the id of this image on image load like,

$(img).load(function() {
// Here I want to get image id i.e. test_img
});

Can you please help me?

Thanks.

+2  A: 
$(img).load(function() {
   var id = $(this).attr("id");
   //etc
});

good luck!!

edit:

   //suggested by the others (most efficient)
   var id = this.id;

   //or if you want to keep using the object
   var $img = $(this);
   var id = $img.attr("id")
Mouhannad
Thanks to all. I think you all are correct. I tried all answers and all worked. Thanks to all of you.
lakum4stackof
+1  A: 
$(img).load(function() {
   alert($(this).attr('id'));
});
Gazler
+5  A: 

Don't use $(this).attr('id'), it's taking the long, inefficient route. Just this.id is necessary and it avoids re-wrapping the element with jQuery and the execution of the attr() function (which maps to the property anyway!).

$(img).load(function() {
   alert(this.id);
});
Andy E
+2  A: 
$(function() {
    $('img#test_img').bind('load', function() {
        console.log(this.id);  //console.log($(this).attr('id'));
    });
});
Ninja Dude