- to add a listener, we use a method called
addEventListener
element.addEventListener(type, functionToCall)
- example:
let button = document.querySelector('button');
button.addEventListener('click', function(){ // callback function, so not called until
console.log("SOMEONE CLICKED THE BUTTON!"); // the button is clicked, then it runs
});
- example of changing text when a button is clicked:
<button>Click Me</button>
<p>No One Has Clicked Me Yet</p>
let button = document.querySelector('button');
let paragraph = document.querySelector('p');
// setup click listener
button.addEventListener('click', function(){
paragraph.textContent = 'Someone Clicked the Button!';
});
- when the button is clicked the text in the paragraph changes
- can have more than one listener on the same element --- they will both run
- example of adding separate listeners to the
li
s in a ul
:let lis = document.querySelectorAll('li');
for(let i = 0; i < lis.length; i++){
lis[i].addEventListener('click', function() {
this.style.color = 'pink'; // `this` in a listener refers to the item the event is on
}); // in this case that would be `lis`
}
- this is very, very common
- can also use named functions
- example:
<button>Click Me</button>
<p>No One Has Clicked Me Yet</p>
let button = document.querySelector('button');
let paragraph = document.querySelector('p');
button.addEventListener('click', changeText);
function changeText(){
paragraph.textContent = 'Someone Clicked the Button!';
}
- this will work exactly the same as the above example with the same set up
- the reason we might use a named (rather than anonymous) function is if we need to use the
code again somewhere else