Created
January 2, 2017 19:36
-
-
Save Anthodpnt/65c9ba636cb7237c92e9b3ccf3c79be8 to your computer and use it in GitHub Desktop.
Misc - Stop Propagation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This gist is for Javascript beginners. | |
* @author: Anthony Du Pont <antho.dpnt@gmail.com> | |
* @site: https://www.twitter.com/JsGists | |
* @codepen: http://codepen.io/JsGists/full/GrKbjx/ | |
* | |
* Binding events in Javascript on an element will propagate these events to every child nodes. | |
* This is a Javascript behavior that will sometimes bother you but Javascript has its own method called | |
* `stopPropagation` that allow us to avoid the propagation of an event. | |
* | |
* Example: | |
* I have 2 containers with a `click` event. Each of them has a button within it with a `click` event too, but only one | |
* of those 2 buttons uses the `stopPropagation` method on the `click` event to stop the propagation of the | |
* event bound to its parent node. Click on the 2 buttons to see the difference. | |
**/ | |
// First we select our containers and their buttons. | |
const a = document.getElementById('a'); // Container A | |
const ba = document.getElementById('ba'); // Button in container A | |
const b = document.getElementById('b'); // Container B | |
const bb = document.getElementById('bb'); // Button in container B | |
// We bind a `click` event on each container. As explained the event is propagated to all | |
// the child nodes. This means you'll see the alert box for each container even if you click | |
// the button because the event is propagated. | |
a.addEventListener('click', (e) => { alert('Click on container A'); }); | |
b.addEventListener('click', (e) => { alert('Click on container B'); }); | |
// We bind a `click` event on each button. The button in the left container doesn't stop the propagation | |
// of the `click` event we have bound to its parent so when you click it you see the alert box of the | |
// button AND the alert box of the container. | |
ba.addEventListener('click', (e) => { alert('Click on button A'); }); | |
// But if you click the button on the right container you'll only see the alert box of the button because | |
// the propagation of the `click` event has been stopped. | |
bb.addEventListener('click', (e) => { | |
// To stop the propagation of a given event, you just need to call the `stopPropagation` method on it. | |
// This line means you don't want the `click` event bound to any parent node to propagate to this element. | |
e.stopPropagation(); | |
alert('Click on button B'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment