2

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.

Dannz
  • 495
  • 8
  • 20
  • Here you have a vanilla javascript solution: https://stackoverflow.com/questions/2705583/how-to-simulate-a-click-with-javascript – jotaelesalinas Mar 15 '19 at 08:21
  • So to dumb down the question....you want to trigger click event on one element to call the click event on other? – CodeBox Mar 15 '19 at 08:24
  • @CodeBox I wouldn't say I want to trigger the click event of the other thing but to change the target itself, the event listen is on tab but there is no event listeners on the otherTab. – Dannz Mar 15 '19 at 08:37

1 Answers1

1

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>
takrishna
  • 4,884
  • 3
  • 18
  • 35
  • 1
    You're right, I've looked it the wrong way. Instead of trying to change the target, I should've triggered the click on the inner element and wait for the event bubbling to happen on the higher element. – Dannz Mar 15 '19 at 10:58
  • what's the point of `ev` in `divClicked` wont it be undefined – Muhammad Omer Aslam May 27 '19 at 22:27