mh108
3/2/2020 - 8:34 PM

Buttons Demo

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <h2>Buttons &#1071; Us</h2>
  <p>
    Click a Button and it will be ID'd.
  </p>
  <button id="btn1">Button1</button>
  <button id="btn2">Button2</button>
  <button id="btn3">Button3</button>
  <br>
  <hr style="width:23%; margin-left:0;">
  <div></div>
  <script src="whichButtonWasClicked.js"></script>
</body>

</html>
// jshint esversion: 6

let $ = function(sel) {
  return document.querySelector(sel);
};


//1. One Ring to Rule Them All
var main = function() {
  //this keyword is set to the button that fired the event
  console.log(this.id);
  //dispatch on button id
  if (this.id == "btn1")
    $("div").innerHTML = "You clicked Button 1";
  else if (this.id == "btn2")
    $("div").innerHTML = "You clicked Button 2";
  else if (this.id == "btn3")
    $("div").innerHTML = "You clicked Button 3";
};

//2. register the onclick handlers after the DOM is complete
window.addEventListener("load", function() {

    //select the buttons
    var buttons = document.querySelectorAll("button");

    //register the same handler for each button
    for (var i = 0; i < buttons.length; ++i) {
        buttons[i].addEventListener("click", main);
    }
});