0

I need a custom context menu, so I use addEventListener for it, but I wish to have it on the div1, but not on div2, how I can do it without to add the same listener with stopPropagation()

<html>
<head>
</head>
<body>
<div id="div1" style="background-color:green;border:3px solid black;width:300px;height:300px;margin:auto;">
<div id="div2" style="background-color:yellow;border:3px solid black;width:100px;height:100px;margin:auto;margin-top:-50px;">
some text
</div>
</div>
<script>
document.getElementById('div1').addEventListener('contextmenu', function(e)
    {
    console.log('contextmenu');
    });
</script>
</body>
</html>
1
  • if (e.target === this) console.log...
    – adeneo
    Jul 16, 2013 at 16:58

2 Answers 2

3

Just check the event target in the handler, and abort if the target was <div2>.

0
0

Add false as a third parameter of addEventListener

document.getElementById('div1').addEventListener('contextmenu', function(e)
{
    console.log('contextmenu');
}, false);

Or if(e.currentTarget.getAttribute("id") != "div1") e.preventDefault();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.