Events
Events¶
Features:¶
- interact with user-action(btn click) and browser-action(on window load)using JS.
-
eg:
window.onload = (e) => {console.log("Windows Loaded")} onload is event listener anonymous fn is event handler. e is event object which get fired. inspect it for for info.
-
Add multiple event listener:
addEventListener(eventListener, eventHandler)
CASE 1 : incorrrect btn.onclick = (e) => {console.log("btn clicked 1")} btn.onclick = (e) => {console.log("btn clicked 2")} // overrides first one. CASE 2: working eh1 = (e) => {console.log("btn clicked 1")} eh2 = (e) => {console.log("btn clicked 2")} btn.addEventListener('click' , eh1 ) //its click not onclick here. btn.addEventListener('click' , eh2 )
- Remove listener :
removeEventListener(eventListener, eventHandler)
-
eg : After 2 seconds removing listener:
-
Events Prophogation:
Add click listener on both div. if we click inner div then technically also clicking div2. both event handler would get called.<div id="outter"> <div id="inner"> </div> </div>
-
addEventListener(eventListener, eventHandler, true)
--> 3rd arg is true. Use it inside parent element's event handler --> it will set the priority high. parent handler will get called first followed by child's event handler. -
stop propagation:
event.stopPropagation()
-
get the element --> who has fired the event.
event.target
- eg : Setting style for element.
- CAn also get the coordinated from where event has been clicked.
Events:¶
-
Mouse Event:
-
Keyboard Event:
-
Forms Event:
note: Check more on mozilla network.