'Dispatch events using new MouseEvent directly to one target (avoiding the dom parents)

I have a wrapper, and two inner layers inside, one above another. The normal behavior is that only "downlayer" receive the events.

I want to send events to "upperlayer", so... I define an eventlistener connected to the wrapper and dispatch a mouseevent to the UpperLayer

If you dont connect this listener you can see how only downlayer receive the events.

However, if you connect the listener an dispatch the event you have a max stack error, because the mouse event starts again from "top" wrapper.

The fix is to have a var 'eventLaunched' false / and true ..

Is there any other idea?

<html>
    <body id="theBody" style="position:absolute; top:0; bottom:0; left:0; right:0;">
        <div id="top" style="width:100%;height:100%;position: absolute;"> 
            <div id="UpperLayer" style="width: 100%;height:100%;border: 1px solid red;position: absolute;top: 0;left: 0;">                
            </div>
            <div id="DownLayer" style="width:100%;float: none; height:100%;border: 1px solid blue;margin: 100px;position: absolute; top: 0;left: 0px;">                </div>
        </div>

       var id1=document.getElementById("top");
        id1.addEventListener("click", rise_event_to_upper, true);

        var id2_1=document.getElementById("UpperLayer");
        id2_1.addEventListener("click", doSomethingUpper, true);   // capture phase
        var id2_2=document.getElementById("DownLayer");
        id2_2.addEventListener("click", doSomething, true);

        var eventLaunched=false;
        function rise_event_to_upper(e) {  
           if (eventLaunched==true) 
           { eventLaunched=false; return;}

           eventLaunched=true;
            console.log("define & dispatch");
            var evt = new MouseEvent("click", {
                bubbles: false,
                cancelable: true,
                view: window,
            });
            document.getElementById("UpperLayer").dispatchEvent(evt);      
        }
        function doSomething(e) {  
         console.log ("capture down");
        }
        function doSomethingUpper(e) {                 
            console.log ("capture upper");
            
        }
        
        function doSomethingUpper2(e) {    
            console.log ("bubling");
            e.stopPropagation();
        }
    </body>
</html>


Solution 1:[1]

You could use mousedown event to bind the rise_event_to_upper function to.

https://jsfiddle.net/sukbxo02/

document.getElementById("top")
            .addEventListener("mousedown", rise_event_to_upper, true);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1