2020年4月24日 星期五

[JS] Onclick listener confusion in div inside div

Background
Sometimes we face situations when we have 2 layers of components (e.g. DIVs), while original (outer) div already configured with onclick listener but on top of the parent div, we also want the child div to have the same onClick listener.


Needless to say, the onclick action listener will be at the top will be fired first, and the parent one (underneath), which is not what we want, we want only child one to be detected and fired events


Solutions
This is related to event bubbling and event capturing. For event bubbling, clicking the inside DIV will trigger the event outside DIV, we need to stop both bubbling event and capturing event by e.stopPropagation and e.cancelBubble

References

沒有留言:

張貼留言