JavaScript Event Listeners:
JavaScript Event Listeners:
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. you can add many event handlers to one element.
element.addEventListener(event,function,useCapture);
Example:
element.addEventListner(“click” myfunction);
element.addEventListner(“mouseover” myfunction);
function myfunction(){
alert(“Hello World”);
}
Let’s create an event handler that removes itself after being executed.
<button id =”demo”> Start </button>
<Script>
var.btn = document.getElementById(“demo”);
btn.addEventListener(“click”,myfunction);
function myfunction(){
alert(Math.random());
btn.removeEventListner(“click”,myfunction);
}
</Script>
Event Propagation:
These are two way of event propagation in the HTML DOM: bubbling and Capturing
Note:
Capturing goes to down DOM
Bubbling goes up the DOM
Capturing vs Bubbling in JavaScript:
//Capturing Propagation
elem1.addEventListener(“click”, myfunction, true);
//Bubbling Propagation
elem2.addEventListener (“click”, myfuncation, false);
Image Slider in JavaScript:
let’s Create our HTML, which includes an img and the two navigation buttons.
<div>
<button> prev </button>
<img id = ” slider” src = “https://www.boomitechie.com/upload/slider/i.jpg” width = “200px” height = “1000”/>
<button>Next</button>
</div>
JavaScript:
v image = [“http://www.boomitechie.com/upload/slider/i.jpg” , ” , “];
Image Slider:
Now are need to handle the Next and Prev button clicks and call the corresponding function to change the image.
HTML:
<div>
<button Onclick = “prev ()”>prev </button>
<img id = “slider” src = “https://www.boomitechie.com”/uploads/slider/1.jpg width = “200 px” height = “100px”/>
<button onclick = “next()”> Next</button>
</div>
JavaScript:
var images = [“https://www.boomitechie.com/upload/slider/i.jpg”, , ” , “];
var num = 0;
function next(){
var slider = document.getElementById(“slider”);
num++;
if(num>=image.length){
num = 0;
}
slider.src = image.[num];
}
function prev(){
var slider =document.setElementById(“slider”);
num–;
if(num<0){
num = image.length-1;
}
slider.sre = image[num];
}
Note: num variable holds the current image.
Technical content writer with data scientist, artificial intelligence, programming language, database. He has a bachelor’s degree in IT and a certificate in digital marketing, Digital transformation web development android app development He has written for website like Boomi techie, tech mantra, information hub, Tech all