顯示具有 propagation 標籤的文章。 顯示所有文章
顯示具有 propagation 標籤的文章。 顯示所有文章

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