SlideShare a Scribd company logo
1 of 5
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
Events >>
Events are actions or occurrences that happen in the system you are programming — the system will fire a
signal of some kind when an event occurs, and also provide a mechanism by which some kind of action can be
automatically taken (e.g. some code running) when the event occurs.
Registering Event Handlers >>
 Event Handler Properties
<button>
Change color
</button>
<script>
var btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random()*(number+1));
}
btn.onclick = function() {
var rndCol = 'rgb(' + random(255) + ',' +
random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
</script>
var btn = document.querySelector('button');
function bgChange() {
var rndCol = 'rgb(' + random(255) + ',' +
random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
btn.onclick = bgChange;
 Inline Event Handler(Bad Practice):
<button onclick="bgChange()">
Press me
</button>
function bgChange() {
var rndCol = 'rgb(' + random(255) +
',' + random(255) + ',' + random(255)
+ ')';
document.body.style.backgroundColor
= rndCol;
}
 addEventListener() and removeEventListener() methods:
var btn = document.querySelector('button');
function bgChange() {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255)
+ ')';
document.body.style.backgroundColor = rndCol;
}
btn.addEventListener('click', bgChange);
advantages:
- You can remove event handler code of needed.
- You can add multiple listeners of the same type to elements if required.
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
Event Object >>
Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt,
or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and
information.
Properties Methods
type
– returns the type/name of
the event
preventDefault() – cancels the event(if it is cancelable)
stopPropagation() – stops the propagation of events further along in the DOM
Example
var form = document.querySelector('form');
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
var submit = document.getElementById('submit');
var para = document.querySelector('p');
form.onsubmit = function(e) {
if (fname.value === '' || lname.value === '') {
e.preventDefault();
para.textContent = 'You need to fill in both names!';
}
}
target
– returns the element that
triggers the event
Major Events List >>
Event Name Description Sample Code
load A resource and its
dependent resources
have finished loading.
<html>
<body onload="myFunction()">
<h1>Hello World!</h1>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body>
</html>
focus The focus event fires
when an element has
received focus.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Events</title>
</head>
<body>
<form id="form">
<input type="text" placeholder="text input">
<input type="password" placeholder="password">
</form>
<script type="text/javascript">
const password =
document.querySelector('input[type="password"]');
blur An element has lost
focus
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
password.addEventListener('focus',function
(event){
event.target.style.background = 'pink';
});
password.addEventListener('blur', (event) => {
event.target.style.background = '';
});
</script>
</body>
</html>
submit The submit button is
pressed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Events</title>
</head>
<body>
<form id="form">
<label>Test field: <input type="text"></label>
<br><br>
<button type="submit">Submit form</button>
<button type="reset">Reset form</button>
</form>
<p id="log"></p>
<script type="text/javascript">
function logSubmit(event) {
log.textContent = `Form Submitted! Time stamp:
${event.timeStamp}`;
event.preventDefault();
}
function logReset(event) {
log.textContent = `Form reset! Time stamp:
${event.timeStamp}`;
}
const form = document.getElementById('form');
const log = document.getElementById('log');
form.addEventListener('submit', logSubmit);
form.addEventListener('reset', logReset);
</script>
</body>
</html>
reset The reset button is
pressed
keydown ANY key is pressed <!DOCTYPE html>
<html>
<body>
<p>A function is triggered when the user releases a key in
the input field. The function transforms the character to
upper case.</p>
Enter your name: <input type="text" id="fname"
onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
keyup ANY key is released
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
</body>
</html>
click A pointing device button
(ANY button; soon to be
primary button only)
has been pressed and
released on an element.
<!DOCTYPE html>
<html>
<body>
<h1>The onclick Event</h1>
<p>The onclick event is used to trigger a function when an
element is clicked on.</p>
<p>Click the button to trigger a function that will output
"Hello World" in a p element with id="demo".</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello
World";
}
</script>
</body>
</html>
dblclick A pointing device button
is clicked twice on an
element.
mousedown A pointing device button
is pressed on an
element.
<!DOCTYPE html>
<html>
<body>
<div style="text-align:center;" id="notification"></div>
<div style="margin:20px;border:1px solid
blue;padding:20px;height:300px;width:auto;background-
color:#ffe6e6;"
onmousedown="mouseeventfn(event);"
onmouseup="mouseeventfn(event);"
onmouseover="mouseeventfn(event);"
onmouseout="mouseeventfn(event)";
onmouseenter="mouseeventfn(event);"
onmouseleave="mouseeventfn(event);">
<div style="margin:50px;border:1px solid
black;padding:50px;background-color:#e6ffee;">
Child
</div>
</div>
<script>
function mouseeventfn(event) {
console.log(event);
document.querySelectorAll("#notification")[0].innerHTML="Event
Type: "+event.type+" Screen X and Y:
"+event.screenX+","+event.screenY+" Window X and Y:
"+event.clientX+","+event.clientY+" Document X and Y:
mouseup A pointing device button
is released over an
element.
mouseenter A pointing device is
moved onto the
element that has the
listener attached.
mouseleave A pointing device is
moved off the element
that has the listener
attached.
mousemove A pointing device is
moved over an element.
(Fired continously as the
mouse moves.)
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
"+event.pageX+","+event.pageY+" Offset X and Y:
"+event.offsetX+","+event.offsetY;
}
</script>
</body>
</html>
change The change event is
fired for <input>,
<select>, and <textarea>
elements when an
alteration to the
element's value is
committed by the user.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<p>When you select a new car, a function is triggered
which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You
selected: " + x;
}
</script>
</body>
</html>
References:
1. https://developer.mozilla.org/en-US/docs/Web/Events
2. https://www.w3schools.com/jsref/dom_obj_event.asp

More Related Content

What's hot (20)

jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
jQuery
jQueryjQuery
jQuery
 
J query
J queryJ query
J query
 
Learn css3
Learn css3Learn css3
Learn css3
 
J query1
J query1J query1
J query1
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery
jQueryjQuery
jQuery
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
jQuery
jQueryjQuery
jQuery
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
 
22 j query1
22 j query122 j query1
22 j query1
 
Jquery
JqueryJquery
Jquery
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 

Similar to Web 5 | JavaScript Events

Similar to Web 5 | JavaScript Events (20)

Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
 
JavaScript-L20.pptx
JavaScript-L20.pptxJavaScript-L20.pptx
JavaScript-L20.pptx
 
Javascript event handler 2
Javascript event handler 2Javascript event handler 2
Javascript event handler 2
 
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireUn-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
 
course js day 3
course js day 3course js day 3
course js day 3
 
Client Web
Client WebClient Web
Client Web
 
5 .java script events
5 .java script   events5 .java script   events
5 .java script events
 
types of events in JS
types of events in JS types of events in JS
types of events in JS
 
JQuery
JQueryJQuery
JQuery
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
 
Javascript 2
Javascript 2Javascript 2
Javascript 2
 
Java scriptfunction
Java scriptfunctionJava scriptfunction
Java scriptfunction
 
Events
EventsEvents
Events
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
 
ReactJS
ReactJSReactJS
ReactJS
 
Java script programms
Java script programmsJava script programms
Java script programms
 
J Query Presentation of David
J Query Presentation of DavidJ Query Presentation of David
J Query Presentation of David
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
 

More from Mohammad Imam Hossain

DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchMohammad Imam Hossain
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionMohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaMohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaMohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckMohammad Imam Hossain
 

More from Mohammad Imam Hossain (20)

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic ProgrammingDS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
 

Recently uploaded

What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxCeline George
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 

Recently uploaded (20)

What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 

Web 5 | JavaScript Events

  • 1. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Events >> Events are actions or occurrences that happen in the system you are programming — the system will fire a signal of some kind when an event occurs, and also provide a mechanism by which some kind of action can be automatically taken (e.g. some code running) when the event occurs. Registering Event Handlers >>  Event Handler Properties <button> Change color </button> <script> var btn = document.querySelector('button'); function random(number) { return Math.floor(Math.random()*(number+1)); } btn.onclick = function() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } </script> var btn = document.querySelector('button'); function bgChange() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } btn.onclick = bgChange;  Inline Event Handler(Bad Practice): <button onclick="bgChange()"> Press me </button> function bgChange() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; }  addEventListener() and removeEventListener() methods: var btn = document.querySelector('button'); function bgChange() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } btn.addEventListener('click', bgChange); advantages: - You can remove event handler code of needed. - You can add multiple listeners of the same type to elements if required.
  • 2. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Event Object >> Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. Properties Methods type – returns the type/name of the event preventDefault() – cancels the event(if it is cancelable) stopPropagation() – stops the propagation of events further along in the DOM Example var form = document.querySelector('form'); var fname = document.getElementById('fname'); var lname = document.getElementById('lname'); var submit = document.getElementById('submit'); var para = document.querySelector('p'); form.onsubmit = function(e) { if (fname.value === '' || lname.value === '') { e.preventDefault(); para.textContent = 'You need to fill in both names!'; } } target – returns the element that triggers the event Major Events List >> Event Name Description Sample Code load A resource and its dependent resources have finished loading. <html> <body onload="myFunction()"> <h1>Hello World!</h1> <script> function myFunction() { alert("Page is loaded"); } </script> </body> </html> focus The focus event fires when an element has received focus. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Events</title> </head> <body> <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> <script type="text/javascript"> const password = document.querySelector('input[type="password"]'); blur An element has lost focus
  • 3. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com password.addEventListener('focus',function (event){ event.target.style.background = 'pink'; }); password.addEventListener('blur', (event) => { event.target.style.background = ''; }); </script> </body> </html> submit The submit button is pressed <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Events</title> </head> <body> <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="submit">Submit form</button> <button type="reset">Reset form</button> </form> <p id="log"></p> <script type="text/javascript"> function logSubmit(event) { log.textContent = `Form Submitted! Time stamp: ${event.timeStamp}`; event.preventDefault(); } function logReset(event) { log.textContent = `Form reset! Time stamp: ${event.timeStamp}`; } const form = document.getElementById('form'); const log = document.getElementById('log'); form.addEventListener('submit', logSubmit); form.addEventListener('reset', logReset); </script> </body> </html> reset The reset button is pressed keydown ANY key is pressed <!DOCTYPE html> <html> <body> <p>A function is triggered when the user releases a key in the input field. The function transforms the character to upper case.</p> Enter your name: <input type="text" id="fname" onkeyup="myFunction()"> <script> function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> keyup ANY key is released
  • 4. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com </body> </html> click A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element. <!DOCTYPE html> <html> <body> <h1>The onclick Event</h1> <p>The onclick event is used to trigger a function when an element is clicked on.</p> <p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p> <button onclick="myFunction()">Click me</button> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } </script> </body> </html> dblclick A pointing device button is clicked twice on an element. mousedown A pointing device button is pressed on an element. <!DOCTYPE html> <html> <body> <div style="text-align:center;" id="notification"></div> <div style="margin:20px;border:1px solid blue;padding:20px;height:300px;width:auto;background- color:#ffe6e6;" onmousedown="mouseeventfn(event);" onmouseup="mouseeventfn(event);" onmouseover="mouseeventfn(event);" onmouseout="mouseeventfn(event)"; onmouseenter="mouseeventfn(event);" onmouseleave="mouseeventfn(event);"> <div style="margin:50px;border:1px solid black;padding:50px;background-color:#e6ffee;"> Child </div> </div> <script> function mouseeventfn(event) { console.log(event); document.querySelectorAll("#notification")[0].innerHTML="Event Type: "+event.type+" Screen X and Y: "+event.screenX+","+event.screenY+" Window X and Y: "+event.clientX+","+event.clientY+" Document X and Y: mouseup A pointing device button is released over an element. mouseenter A pointing device is moved onto the element that has the listener attached. mouseleave A pointing device is moved off the element that has the listener attached. mousemove A pointing device is moved over an element. (Fired continously as the mouse moves.)
  • 5. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com "+event.pageX+","+event.pageY+" Offset X and Y: "+event.offsetX+","+event.offsetY; } </script> </body> </html> change The change event is fired for <input>, <select>, and <textarea> elements when an alteration to the element's value is committed by the user. <!DOCTYPE html> <html> <body> <p>Select a new car from the list.</p> <select id="mySelect" onchange="myFunction()"> <option value="Audi">Audi</option> <option value="BMW">BMW</option> <option value="Mercedes">Mercedes</option> <option value="Volvo">Volvo</option> </select> <p>When you select a new car, a function is triggered which outputs the value of the selected car.</p> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("mySelect").value; document.getElementById("demo").innerHTML = "You selected: " + x; } </script> </body> </html> References: 1. https://developer.mozilla.org/en-US/docs/Web/Events 2. https://www.w3schools.com/jsref/dom_obj_event.asp