JS7 ClassNotes
JS7 ClassNotes
ege
Events are fired to notify code of "interesting changes" that may affect code execution.
l
Col
a
<button onclick="console.log('button was clicked');alert
pn
('hello')">Click Me</button> in html onclick krne se we can
A
link any event to the btn.
Mouse events (click, double click etc.)
<button ondblclick="console.log('button was clicked');alert
Keyboard events (keypress, keyup, keydown) ('hello')">Click Me 2 times</button> in html it is used
when btn is clicked two times.
Form events (submit etc.)
<div onmouseover="console.log('you are inside div')"> this is a box</div>
Print event & many more jaise hi div ke andar cursor jayega console me wo likha hua aa jayega.
Inline event handling=jo console.log likhte hai same line me use kehte h .
Event Handling in JS
e
node.event = ( ) => {
leg
//handle here
ol
}
na C
Ap
example
btn.onclick = ( ) => { inline event handling is bekar . make a function like this and then use.
do bar kisi ko define nahi kr skte JS same cheez likhenge dobara kuch change
krk to override ho jayega
Event Object
It is a special object that has details about the event.
lege
All event handlers have access to the Event Object's properties and methods.
Col
pna
btn1.onclick=(evt)=>{
node.event = (e) => {
A
console.log(evt);
//handle here console.log(evt.type);
console.log(evt.target);
} console.log(evt.clientX,evt.clientY);
similar to an object.
e
onclick,onmouseover etc. btn1.addEventListener("click",()=>{
node.addEventListener( event, callback )
g
console,log("button was clicked-handler 2");
e
});
l
function/handler
ol
now this time on clicking the button both events will console
C
on log at the same time not overriding the other as in prev case
pna btn1.addEventListener("click",(evt)=>{
A
*Note : the callback reference should be same to remove console.log("button was clicked");
console.log(evt.type);
});
btn1.addEventListener("click",()=>{ we can access event object also like this.
console,log("button was clicked-handler 2");
});
btn1.removeEventListener("click",()=>{
console,log("button was clicked-handler 2");
});
instead we can store the func in a variable and then remove
we notice that handler 2 is not removed on doing the
above op because the function(i.e. the part after"click",) const handler=()=>{
have different spaces in memory console.log("button was clicked-handler2");
so callback reference should be same to remove as written above. };
btn1.removeListener("click",handler);
Let‘s Practice
Qs. Create a toggle button that changes the screen to dark-mode when clicked & light-mode
e
when clicked again.
lleg
a Co
Apn