HTML
<input type="text" placeholder="name" id="nameInput"> <button id="submitButton">Submit</button> <button id="winnerButton">Pick winner</button> <p id="winnerParagraph"></p>
JavaScript
let nameInput = document.getElementById(`nameInput`) let submitButton = document.getElementById(`submitButton`) let winnerButton = document.getElementById(`winnerButton`) let winnerParagraph = document.getElementById(`winnerParagraph`) let names = [] submitButton.addEventListener(`click`, submit) winnerButton.addEventListener(`click`, pickWinner) function submit() { names = nameInput.value } function pickWinner() { let randomNumber = Math.floor(Math.random() * names.length) winnerParagraph.innerHTML = names[randomNumber] }
Reason
HTML
<input type="text" placeholder="name" id="nameInput"> <button id="submitButton">Submit</button> <button id="winnerButton">Pick winner</button> <p id="winnerParagraph"></p>
JavaScript
let nameInput = document.getElementById(`nameInput`) let submitButton = document.getElementById(`submitButton`) let winnerButton = document.getElementById(`winnerButton`) let winnerParagraph = document.getElementById(`winnerParagraph`) let names = [] submitButton.addEventListener(`click`, submit) winnerButton.addEventListener(`click`, pickWinner) function submit() { names.push(nameInput.value) } function pickWinner() { let randomNumber = Math.floor(Math.random() * names) winnerParagraph.innerHTML = names[randomNumber] }
Reason
HTML
<input type="text" placeholder="name" id="nameInput"> <button id="submitButton">Submit</button> <button id="winnerButton">Pick winner</button> <p id="winnerParagraph"></p>
JavaScript
let nameInput = document.getElementById(`nameInput`) let submitButton = document.getElementById(`submitButton`) let winnerButton = document.getElementById(`winnerButton`) let winnerParagraph = document.getElementById(`winnerParagraph`) let names = [] submitButton.addEventListener(`click`, submit) winnerButton.addEventListener(`click`, pickWinner) function submit() { names.push(nameInput.value) } function pickWinner() { let randomNumber = Math.floor(Math.random() * names.length) winnerParagraph.innerHTML = names }
Reason
HTML
<button class="button">Button 1</button> <button class="button">Button 2</button> <button class="button">Button 3</button>
JavaScript
let buttons = document.getElementsByClassName(`button`) buttons.addEventListener(`click`, changeColor) function changeColor() { this.style.backgroundColor = `yellow` }
Reason
HTML
<button class="button">Button 1</button> <button class="button">Button 2</button> <button class="button">Button 3</button>
JavaScript
let buttons = document.getElementsByClassName(`button`) for (let button of buttons) { button.addEventListener(`click`, changeColor) } function changeColor() { button.style.backgroundColor = `yellow` }
Reason