I'm trying to find the jQuery equivalent of this JavaScript method call:
document.addEventListener('click', select_element, true);
I've gotten as far as:
$(document).click(select_element);
but that doesn't achieve the same result, as the last parameter of the JavaScript method - a boolean that indicates whether the event handler should be executed in the capturing or bubbling phase (per my understanding from http://www.quirksmode.org/js/events_advanced.html) - is left out.
How do I specify that parameter, or otherwise achieve the same functionality, using jQuery?
This question is related to
javascript
jquery
events
event-handling
dom-events
Here is an excellent treatment on the Mozilla Development Network (MDN) of this issue for standard JavaScript (if you do not wish to rely on jQuery or understand it better in general):
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
Here is a discussion of event flow from a link in the above treatment:
http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
Some key points are:
You should now use the .on()
function to bind events.
One thing to note is that jQuery event methods do not fire/trap load
on embed
tags that contain SVG DOM which loads as a separate document in the embed
tag. The only way I found to trap a load
event on these were to use raw JavaScript.
This will not work (I've tried on
/bind
/load
methods):
$img.on('load', function () {
console.log('FOO!');
});
However, this works:
$img[0].addEventListener('load', function () {
console.log('FOO!');
}, false);
As of jQuery 1.7, .on()
is now the preferred method of binding events, rather than .bind()
:
From http://api.jquery.com/bind/:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
The documentation page is located at http://api.jquery.com/on/
$( "button" ).on( "click", function(event) {_x000D_
_x000D_
alert( $( this ).html() );_x000D_
console.log( event.target );_x000D_
_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<button>test 1</button>_x000D_
<button>test 2</button>
_x000D_
The closest thing would be the bind function:
$('#foo').bind('click', function() {
alert('User clicked on "foo."');
});
Source: Stackoverflow.com