Mikhail Edoshin
Mikhail Edoshin

Reputation: 2669

Listen for `mousedown` on parent but let `click` to pass to children

I have a div that listens for mousedown event. The div has some child buttons (absolutely positioned outside the div). I want to be able to click these buttons. But when I press the mouse button, the parent div intercepts the mousedown event. I can test the .target member to ignore the event if it happened on the buttons, but it seems that I never get the click event on these buttons this way.

Is there a way to solve this without adding yet another ancestor div?

Upvotes: 3

Views: 2073

Answers (1)

Ehsan
Ehsan

Reputation: 12951

You can use event.target == this

Example :

<html>
    <head>
       <style>
           div {
               width: 100px;
               background-color: yellow;
               height: 100px;
           }
       </style>
    </head>
    <body>
        <div id="d">I am div
            <button id="btn1">Button1</button>
        </div>
        <script>
            var divMousedown = document.getElementById("d");
            var Child = document.getElementById("btn1");
            divMousedown.onmousedown = function(event) {
                if(event.target == this)
                alert("You Mouse down on Div");
            }
            Child.onclick = function(event){
                if(event.target == this)
                    alert("You Click on Button")
            }
        </script>
    </body>
</html>

Upvotes: 2

Related Questions