Asim Zaidi
Asim Zaidi

Reputation: 28284

Show ID for image clicked

My HTML is like so:

    <img src="/path" id="img_1">
    <img src="/path" id="img_2">
    <img src="/path" id="img_3">
    <img src="/path" id="img_4">

I want to alert out the id of the button that was clicked.

How can I accomplish that?

Upvotes: 1

Views: 10764

Answers (3)

Naftali
Naftali

Reputation: 146302

$('img').click(function(){
   alert(this.id);
}); //try that :-)

DEMO

Or a more 'dynamic version' (if you are adding the images by ajax or some other implementation):

$('img').live('click', function(){
   alert(this.id);
}); //try that :-)

Upvotes: 5

Chad
Chad

Reputation: 19609

With jQuery:

$('img').click(function() {
   alert($(this).attr('id'));
});

Or plain JS:

function handleClick(sender) {
   alert(sender.id);
}

<img src="/path" id="img_1" onclick="handleClick(this);" />
<img src="/path" id="img_2" onclick="handleClick(this);" />
<img src="/path" id="img_3" onclick="handleClick(this);" />
<img src="/path" id="img_4" onclick="handleClick(this);" />

Upvotes: 2

$("img").click(function() {
  alert($(this).attr("id"));
});

Upvotes: 4

Related Questions