File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
25 - Event Capture, Propagation, Bubbling and Once Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 5959
6060< script >
6161
62+ function playSound ( e )
63+ {
64+ const audio = document . querySelector ( `audio[data-key="${ e . keyCode } "]` ) ;
65+ // using classes is more messier here - const audio = document.querySelector('.key-65');
66+
67+ const key = document . querySelector ( `.key[data-key="${ e . keyCode } "]` ) ;
68+
69+ if ( ! audio ) return ; //stop function running
70+ audio . currentTime = 0 ; //rewind audio clip to the start
71+ audio . play ( ) ;
72+ key . classList . add ( 'playing' ) ;
73+
74+ }
75+
76+ window . addEventListener ( 'keydown' , playSound ) ;
77+
78+ function removeTransition ( e )
79+ {
80+ console . log ( e . propertyName ) ;
81+ if ( e . propertyName != 'transform' ) return ;
82+ this . classList . remove ( 'playing' ) ;
83+ }
84+
85+ const keys = document . querySelectorAll ( '.key' ) ;
86+ keys . forEach (
87+ ( key ) => {
88+ key . addEventListener ( 'transitionend' , removeTransition ) ;
89+ }
90+ ) ;
91+
6292</ script >
6393
6494
Original file line number Diff line number Diff line change 4242
4343< button > </ button >
4444< script >
45+ const divs = document . querySelectorAll ( 'div' ) ;
46+ const button = document . querySelector ( 'button' ) ;
47+
48+ function logText ( e )
49+ {
50+ console . log ( this ) ;
51+ console . log ( this . classList . value ) ;
52+ e . stopPropagation ( ) ; //will prevent bubbling up
53+ }
54+
55+ divs . forEach (
56+ ( div ) => div . addEventListener ( 'click' , logText , {
57+ capture :false ,
58+ once :true
59+ } )
60+ ) ;
61+
62+ //because we used once:true, "Hi" will get printed only once irrespective
63+ //of how many times we click the button
64+ button . addEventListener ( 'click' ,
65+ ( ) => {
66+ console . log ( "Hi" ) ;
67+ }
68+ , { once :true } ) ;
69+
4570
4671</ script >
4772</ body >
You can’t perform that action at this time.
0 commit comments