+ 4

How can I add a event listener

Please make a sample code in web

6th Nov 2020, 4:19 PM
đŸ„‡đŸ‘©â€đŸ’» Kintu Michael Evans đŸ”„đŸ”„( Active)
đŸ„‡đŸ‘©â€đŸ’» Kintu Michael Evans đŸ”„đŸ”„( Active) - avatar
1 Answer
+ 6
first grab an element from DOM There are a few ways in which you can do that, im just gonna show you the common ways: 1) using element's id document.getElementById("myButton") 2) using selectors that you use in css such as dot for classes and hash for ids let myBtn = document.querySelector("#myButton") myBtn.addEventListener("click", function(e) { /* runs everytime you click, and i passed (e) as a paremeter which is EVENT that we automatically receive in these kind of functions */ console.log("button clicked!") }) you could also do it like this: myBtn.onclick = function(e) { console.log(e.target) //shows you the whole tag on which event occurred so in this case <button id="myButton">Btn</button> }
6th Nov 2020, 4:40 PM
maf
maf - avatar