Question

I have a button that has a style

pointer-events: none;

And this button has a parent element that performs a collapsible event. I don't know how to prevent this button from triggering its parent elements collapsible event. This is caused because of the button style which is pointer-events: none

Thanks

Was it helpful?

Solution

Assuming the following html:

<div class="collapsible">
    <button>Hi</button>
</div>

You could do something like this:

$('.collapsible').click(function(e) {
    if ($(this).children('button').css('pointer-events') == 'none') return;

    //do collapse
});

or maybe this:

$('.collapsible').click(function(e) {        
    //do collapse
});

$('.collapsible button').click(function(e) {
   if ($(this).css('pointer-events') == 'none')
       e.stopPropagation();
});

OTHER TIPS

As @adeneo said, if you use pointer-events: none on the child, then parent's event listener can't know if the target is itself or its child. It's like when you click some text inside a paragraph, the event listener can't know if you clicked the text or paragraph's padding.

Then, you can use

document.getElementById('outer').onclick = function(e) {
    /* your code */
};
document.getElementById('outer').addEventListener('click',  function(e) {
    if(e.target !== this) {
        e.stopPropagation();
    }
}, true);

WITHOUT pointer-events: none.

This way, you use capture phase, so you can prevent the execution of children's event handlers (like pointer-events: none), but now you can distinguish if the user clicked your element or its children.

Demo jsFiddle

Problem: You can't use capture phase on old versions of IE.

Advantage: Since it doesn't work on old IE, you don't have to worry about things like

  • e = e || window.event
  • e.target || e.srcElement
  • if (e.stopPropagation) { e.stopPropagation(); } else { e.calcelBubble=true; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top