Skip to content

Live coding: JavaScript in the browser

Event listener with named function

View in browser

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

View in browser

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

View in browser

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

View in browser

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)

Content CC BY 4.0 | Code AGPL 3.0