Created
October 7, 2016 20:24
-
-
Save MikeDigitize/7c70524caa6d9f91d845ce836757993c to your computer and use it in GitHub Desktop.
How to capture click events on parent elements when multiple listeners are registered without triggering on the wrong parent
This file contains hidden or 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
| <style> | |
| .buy { | |
| margin-bottom: 20px; | |
| } | |
| </style> | |
| <div class='container'> | |
| <div class='mini-basket'> | |
| <button class='buy'>Buy Mini Basket</button> | |
| <div class='basket-inner'> | |
| <button class='buy'>Buy basket inner</button> | |
| </div> | |
| </div> | |
| <button class='buy'>Out of basket</button> | |
| </div> | |
| <script> | |
| var BuyButton = (function() { | |
| function BuyButton(parent = document.body) { | |
| if(!(this instanceof BuyButton)) { | |
| return new BuyButton(parent); | |
| } | |
| this.parent = parent instanceof HTMLElement ? parent : document.querySelector(parent); | |
| this.boundClickReference = this.onClick.bind(this); | |
| this.parent.addEventListener('click', this.boundClickReference, false); | |
| } | |
| var _$ = BuyButton.prototype; | |
| _$.onClick = function(evt) { | |
| evt.preventDefault(); | |
| this.catchClick(evt, evt.target || evt.srcElement); | |
| }; | |
| _$.catchClick = function(evt, target) { | |
| var parent = target.parentNode; | |
| while(parent) { | |
| if(parent === this.parent) { | |
| evt.stopPropagation(); | |
| this.onCapture(target); | |
| return; | |
| } | |
| parent = parent.parentNode; | |
| } | |
| }; | |
| _$.onCapture = function(target) { | |
| console.log('Found!!', target, this.parent); | |
| }; | |
| return BuyButton; | |
| })(); | |
| var inner = BuyButton('.basket-inner'); | |
| var mini = BuyButton('.mini-basket'); | |
| var con = BuyButton('.container'); | |
| // var noSelector = BuyButton(); // works too | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment