Justin Zhang
Justin Zhang

Reputation: 190

JQuery multiple click event?

There are two div in my page.

<div id="test-1000"></div>
<div id="test-1111"></div>

In view of above single click event source jQuery is:

$('#test-1000').click(function(){});

But how to achieve two div with a similar to the above statement click events to be monitored are, and how to distinguish between div, which is the click event?

Upvotes: 7

Views: 189

Answers (6)

user2882854
user2882854

Reputation: 1

HTML

  <div class="test" id="test-1000" data-id="1000"></div>
    <div class="test" id="test-1111" data-id="1111"></div>

Js

$('.test').click(function(){
    //here this.id will give the clicked div id and this will refer the clicked dom element
    //$(this).data('id') will give 1000/1111
});

Upvotes: 0

Romain Meresse
Romain Meresse

Reputation: 3044

Alternatively, if you don't want or can't modify your html, you can use jquery "starts-with" selector.

<div id="test-1000"></div>
<div id="test-1111"></div>

$("[id^='test']").on('click', function(){
    console.log(this.id);
});

JsFiddle

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

I'll use a common class attribute to group all the target elements

<div class="test" id="test-1000" data-id="1000"></div>
<div class="test" id="test-1111" data-id="1111"></div>

then

$('.test').click(function(){
    //here this.id will give the clicked div id and this will refer the clicked dom element
    //$(this).data('id') will give 1000/1111
})

Upvotes: 10

Ashish Kasma
Ashish Kasma

Reputation: 3642

I prefer to go with data attribute and class approach

HTML code

<div class="test" data="0000">1</div>
<div class="test" data="1111">2</div>

js

$('.test').click(function(){
   alert($(this).attr("data"));
});

sample demo

Upvotes: 0

jbarnett
jbarnett

Reputation: 984

Just use $(this) in the callback function to know 'which' element the event fired on.

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

Upvotes: 2

Jarod Thornton
Jarod Thornton

Reputation: 401

Maybe something like:

document.getElementById("test-1000").onclick = function(){});

You can not use the element before it is defined.

Upvotes: -2

Related Questions