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?
This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.
The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.
The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.
jQuery unbind() Method The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
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
})
Just use $(this)
in the callback function to know 'which' element the event fired on.
$('.test').click( function() {
alert( $(this).attr('id') );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With