Consider the following HTML:
<select value="val2">
<option value="val1">o1</option>
<option value="val2">o2</option>
</select>
And JavaScript (performed on document ready):
var $select = $('select');
var select = $select.get(0);
function logger(msg) {
return function () { console.log(msg); };
}
$select.on('change', logger('jquery on select'));
$(document).on('change', logger('jquery on document'));
select.addEventListener('change', logger('native on select'), false);
document.addEventListener('change', logger('native on document'), false);
setTimeout(function () {
console.log(' == programmatic ==');
$select.trigger('change');
console.log(' == now try manual ==');
}, 1000);
This results to the following output in the console:
== programmatic ==
jquery on select
jquery on document
== now try manual ==
jquery on select
native on select
jquery on document
native on document
The question is: why are natively bound listeners not called? How make them be called?
Here's also a jsFiddle: http://jsfiddle.net/PVJcf/
(Using jQuery 2.0.2)
You need to trigger the default click method, not the one by jQuery. This can be done by adding the default click option within a click event of jQuery using this . This is how the JavaScript looks. It basically creates the event when the DOM is ready, and clicks it intermediately, thus following the link.
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
document. querySelector('#test'). addEventListener('change', () => console. log("Changed!"))
This article gives a good overview of the topic:
Triggering Event Handlers
Basically, trigger
will only fire event handlers attached through jQuery or certain event handler attributes in the html.
You can define a plugin to trigger a native browser event like this:
(function($) {
$.fn.trigger2 = function(eventName) {
return this.each(function() {
var el = $(this).get(0);
triggerNativeEvent(el, eventName);
});
};
function triggerNativeEvent(el, eventName){
if (el.fireEvent) { // < IE9
(el.fireEvent('on' + eventName));
} else {
var evt = document.createEvent('Events');
evt.initEvent(eventName, true, false);
el.dispatchEvent(evt);
}
}
}(jQuery));
// sample usage
$('select').trigger2('change');
This is not perfect but should give you the general idea.
Here's an update to your fiddle using this plugin.
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