Reputation: 495
I want to trigger a click event while changing the event target item. jQuery solution is not mandatory.
The regular triggering works while the custom one doesn't.
This regular example works:
$(tab).trigger('click');
this one, on the other hand, doesn't:
let event = $.Event('click');
event.target = otherTab;
$(tab).trigger(event);
Am I missing anything?
Edit (tried the vanilla way):
let e = new Event('click'); // tab and otherTab are jQuery objects
e.target = otherTab[0];
tab[0].dispatchEvent(e);
Which is triggered but the e.target is not set and still null.
Upvotes: 2
Views: 4817
Reputation: 5002
Based on Element.click() https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
function divClicked(ev){
console.log("Div clicked");
alert("Test");
}
function dispatchToOtherElement(){
let divWithEvent = document.getElementById("divWithEvent");
divWithEvent.click();
}
<div id=divWithEvent onclick="divClicked()">
Element with event
</div>
<div id=divWithoutEvent onclick="dispatchToOtherElement()">
Element without event
</div>
Upvotes: 1