javascript - trigger click event on parent with bubbling -


i want manually fire click event on parent container dispatchevent. event bubbling not seem work.

// trigger click event on parent container parent.dispatchevent(new mouseevent("click", {     bubbles: true,     cancelable: true,     view: window,     clientx: 4,     clienty: 4 })); 

...

child.addeventlistener('click', function(e) {     alert('click') }, false); 

see fiddle:

https://jsfiddle.net/o4j0cjyp/2/

events bubble or not @ all. way know bubble down elements in targeted element, , iterate on collection dispatching event on of them, of them, or whatever situation needs. bad if not tell event not bubble end in infinite loop.

a better way go goal use event delegation, use common parent event listener element. when event happens check event target, if 1 want whatever work.

so html

<div id="parent-container">   <div id="child-container">     area has click listener   </div> </div> <div id="click-info">no 'click' event yet.</div> <div class="btn" id="trigger-parent-btn">   trigger 'click' event on parent container<br>   [ not work ] </div> <div class="btn" id="trigger-child-btn">   trigger 'click' event directly on child container </div> 

instead of setting event listeners on each one, , trying trigger child or parent event, can setup click listener on common parent (in case <body>). in there can test if target element 1 of 3 want trigger showing click info, if show info.

var info = document.queryselector("#click-info");  document.body.addeventlistener("click",function(event){    var target = event.target;    if(target.classlist.contains("btn") || target.id=="child-container"){      info.innerhtml = 'clicked @ ' + event.clientx + ':' + event.clienty;    }  })
<div id="parent-container">    <div id="child-container">      area has click listener    </div>  </div>  <div id="click-info">no 'click' event yet.</div>  <div class="btn" id="trigger-parent-btn">    trigger 'click' event on parent container<br>    [ not work ]  </div>  <div class="btn" id="trigger-child-btn">    trigger 'click' event directly on child container  </div>


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -