What is an Event?
HTML event is a thing that happens to the HTML element.
Eg :
>Page loading
> button was clicked
3 ways of writing event in java script :
test.html :
--------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="para1"> I am child one </p>
<p class="para2"> I am child two </p>
<p> I am child three </p>
<button id="btn1" onclick="change()"> 1st way </button> <br>
<button id="btn2" > 2nd way </button> <br>
<button id="btn3" > 3rd way </button>
<h3 id="update"> You are smart </h3>
<script src=" prac.js"></script>
</body>
</html>
test.js:
----------
let btn1 = document.getElementById("btn1");
let btn2 = document.getElementById("btn2");
let btn3 = document.querySelector("#btn3");
const change = () => {
console.log("clicked");
alert("1st way")
}
//overrides if same event is called multiple timesbtn2.onclick = () =>{
alert("2nd way")
}
//multiple event can be called
btn3.addEventListener('click' , ()=>{
alert("3rd way")
})
What is Event Object ?
Event object is parent object of event object
eg : mouseEvent , focusEvent , keyboardEvent , inputEvents
Input Events (Important) :
Eg1 : onchange event and grab element of form :
HTML file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="main-div">
<label for="">Enter Name</label>
<input type="text" id="name" name="name" placeholder="enter name">
<br>
<label for="">Choose ice-cream falvor</label>
<select id="iceCream" name="icecream" onchange="getElement()">
<option>select any one...</option>
<option value="choclate">Choclate</option>
<option value="mango">Mango</option>
<option value="papaya">Papaya</option>
</select>
<br>
<div class="result" id="result">
</div>
</div>
<script src=" prac.js"></script>
</body>
</html>
js file:
////////////////////////////////inline way////////////////////////
const getElement = () => {
var formname = document.getElementById("name").value
var formselect = document.getElementById("iceCream").value
let result = document.getElementById("result")
result.innerHTML = `<h3> name: ${formname} and select : ${formselect} </h3>`
}
// OR
////////////////////////////////event listner way////////////////////////let iceCream = document.getElementById("iceCream");
iceCream.addEventListener('change', () => {
var formname = document.getElementById("name").value
var formselect = document.getElementById("iceCream").value
let result = document.getElementById("result")
result.innerHTML = `<h3> name: ${formname} and select : ${formselect} </h3>`
});
0 Comments