I want to simulate fake mousedown event by jQuery trigger() method, and I register mousedown event by native javascript method - addEventListener(). And I found it can't be triggered...
elem.addEventListener('mousedown', function () {
alert('addEventListener');
});
$(elem).on('mousedown', function () {
alert('on');
});
$(elem).trigger('mousedown');
Sample in jsFiddle
I do some tests about it.
Is anything wrong here?
Thanks.
P.S. The reason why uses addEventListener() is that I want to write a library without jQuery.
The mousedown event occurs when the left mouse button is pressed down over the selected element. The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs. Tip: This method is often used together with the mouseup() method.
To cause a MouseDown event for a form section to occur, press the mouse button in a blank area of the form section. The following apply to MouseDown events: If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event.
Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.
MouseDown or MouseUp event procedures specify actions that occur when a mouse button is pressed or released. MouseDown and MouseUp events enable you to distinguish between the left, right, and middle mouse buttons.
Try using
EventTarget.dispatchEvent
MDN link
Your code will be something like
var elem = document.getElementById('square');
elem.addEventListener('mousedown', function () {
alert('addEventListener');
});
$(elem).on('mousedown', function () {
alert('on');
});
elem.dispatchEvent(new Event('mousedown'))
You might have to use fireEvent
if you are considering IE.
object.fireEvent(bstrEventName, pvarEventObject, pfCancelled)
MSDN link
It would be like
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent("on" + event.eventType, event);
}
Jquery Only triggers the events that created by itself
Even the order is also matters like : this Works
$(elem).on('mousedown', function () {
alert('on');
});
$(elem).trigger('mousedown');
But Below code Will not Work
$(elem).trigger('mousedown');
$(elem).on('mousedown', function () {
alert('on');
});
Take A look at This DEMO FIDDLE
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