coure2011
coure2011

Reputation: 42454

preventing event default of from child element

How to prevent parent event if child's event is executed. Here is the code see the comments

document.addEventListener('touchend', function (e) { 
    //Do something here
}, false);

someChildElement.addEventListener('touchend', function (e) { 
    //Do something here

    //if this code block is executed then do-not execute the touchend event of document//
}, false);

Upvotes: 0

Views: 83

Answers (3)

Kalpesh Patel
Kalpesh Patel

Reputation: 2822

Use

preventdefault(event) function.

http://api.jquery.com/category/events/event-object/

Upvotes: 0

Golmaal
Golmaal

Reputation: 669

Have you tried changing the event propagation mechanism?

The last parameter in the 'addEventListener' method controls the propagation of event. If we set it to false, the event bubbles but if we set it to true, the event is captured and then it bubbles up. So when we set it to 'true', the "container" receives the event before the "child" and when we set it to 'false', the child receives the event ahead of the container. In simple words, when we set the parameter to 'false', the event registrar starts from inner element as the event bubbles from 'child' element to its container element. And when we set it to 'true', the event registrar first travel downwards to the container element as it is the first element to which the event is registered, traversing the document tree from outermost element and then it reaches to the child element.

And then you can use event.stopPropagation to stop event from traversing further.

You can learn more about it here on MDN

Upvotes: 1

Pavan
Pavan

Reputation: 4329

You can try this in your child event handler

event.stopPropagation()

For Internet Explorer, you should use

window.event.cancelBubble = true

Upvotes: 2

Related Questions