Live coding: JavaScript in the browser
Event listener with named function
html
<button type="button">Add another word: </button>
js
let triggerButton = document.querySelector('button')
function addWord(event) {
let element = event.target
// console.log(element)
element.textContent += ' word'
}
triggerButton.addEventListener('click', addWord)
Event listener with anonymous function
html
<button type="button">Add another word: </button>
js
let triggerButton = document.querySelector('button')
triggerButton.addEventListener('click', function (event) {
let element = event.target
// console.log(element)
element.textContent += ' word'
})
Events on buttons
html
<div id="button-wrapper">
<button value="mustard">Mustard</button>
<button value="red">Red</button>
<button value="blue">Blue</button>
</div>
<section class="flex-container">
<div class="square mustard"></div>
</section>
js
let buttonWrapper = document.querySelector('#button-wrapper')
function changeColor(event) {
let color = event.target.value
let square = document.querySelector('.square')
square.className = `square ${color}`
square.innerHTML = `<div class="color-label">${color}</div>`
}
buttonWrapper.addEventListener('click', changeColor)
Debugging
html
<div id="button-wrapper">
<button value="mustard">Mustard</button>
<button value="red">Red</button>
<button value="blue">Blue</button>
</div>
<section class="flex-container">
<div class="square mustard"></div>
</section>
js
let buttonWrapper = document.querySelectorAll('#button-wrapper')
function changeColor(event) {}
let color = event.value
let square = document.querySelector('.square')
square.className = `square ${color}`
square.innerHTML = `<div class="color-label">${color}</div>`
}
buttonWrapper.addEventListener('click', changeColor)