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'
})

Working with DOM objects

View in browser

html
<section class="flex-container">
  <p>Do They Know It's Christmas?</p>
  <p>Relax</p>
  <p>I Just Called to Say I Love You</p>
  <p>Two Tribes</p>
  <p>Don't You Want Me</p>
</section>
js
let songs = document.querySelectorAll('p')

function remove(event) {
  let p = event.target
  let section = p.parentElement
  section.removeChild(p)
}

function highlightBlue(event) {
  let p = event.target
  p.classList.toggle('blue')
}

for (let song of songs) {
  song.addEventListener('click', remove)
  // song.addEventListener('click', highlightBlue)
}

Using JavaScript on forms

View in browser

html
<form action="" id="background-color-form" method="post">
  <div>
    <label for="color">mustard, red, or blue?</label>
  </div>
  <div>
    <input id="color" name="color">
    <button type="submit">Submit</button>
  </div>
</form>
js
// Make the background color change to the color entered by the user

// Select the form by the element name
let form = document.querySelector('form')

// Select the square div by the class "square"
let square = document.querySelector('.square')

// Defines what to do with the event
function changeColor(event) {

  // First keep the browser from automatically refreshing the whole page.
  event.preventDefault()

  // Then get the target of the event. We know this is the form.
  let form = event.target

  // Get the input where the user typed the color.
  colorInput = form.querySelector('input#color')

  // Reset the classes on the square, including the string entered by the user.
  color = colorInput.value
  square.className = `shape square ${color}`
}

// This ties the form submit event to an action to take
form.addEventListener('submit', changeColor)

Content CC BY 4.0 | Code AGPL 3.0