Event Handling

  1. Overview
    1. JavaScript code is often executed in response to an event
    2. Common events: Mouse click, the page loading, focus being given to a control
    3. A function that executes when an event occurs is called an event handler or callback function
  2. click event
    1. Triggered when the mouse clicks on an element
    2. Using OnEvent HTML attributes
      1. Many onEvent HTML attributes exist, like onclick, onload, onkeypress, etc.
      2. Example shows an alert dialong box when the button is clicked
        <input type="button" value="Click Me" onclick="alert('You clicked the button!')">
        
      3. Putting JavaScript code in-line with HTML is not best practice, and this method is typically not used any more
    3. Traditional event-registration model
      1. Set the click property
        <input type="button" value="Click Me" id="mybutton">
        
        <script>
        	var button = document.getElementById("mybutton");
        	button.onclick = buttonClick;
        	
        	function buttonClick() {
        		alert("You clicked the button!");
        	}
        </script>
        
      2. Considered bad practice because other pre-existing event handlers for click are removed
    4. W3C event-registration model is the preferred method for registering event handlers
      <input type="button" value="Click Me" id="mybutton">
      
      <script>
      	var button = document.getElementById("mybutton");
      	button.addEventListener("click", buttonClick);
      
      	function buttonClick() {
      		alert("You clicked the button!");
      	}
      </script>
      

      Notes:
      1. document.getElementById(id) - Important to execute after the DOM has loaded (more later)
      2. obj.addEventListener("event", handler) - registers an event handler for a particular event. Event handler must be a zero-argument function or a function that takes an event parameter (more later)
      3. addEventListener() can be used on any element like an image, a button, or the document
        // Register event handler for the entire page
        document.addEventListener("click", buttonClick);
        
      4. Common mistake that executes buttonClick() immediately instead of when button is clicked:
        // WRONG!  Don't put () after event handler!
        button.addEventListener("click", buttonClick());
        
      5. Can use an anonymous function:
        button.addEventListener("click", function() { 
        	alert("You clicked the button!") });
        
  3. load and DOMContentLoaded events
    1. load - Triggered when the web page has finished loading (including images, stylesheets, etc.)
    2. DOMContentLoaded - Triggered when the document has been completely loaded and parsed, without waiting for images, stylesheets, and subframes to finish loading
    3. DOMContentLoaded event handler is ideal for registering other event handlers because all DOM elements can now be found by getElementById()
      function start() {
      	// Register event listeners
      	var button = document.getElementById("mybutton");
      	button.addEventListener("click", buttonClick);
      }
      
      // Execute start after the DOM is ready
      window.addEventListener("DOMContentLoaded", start);
      
  4. mouseover and mouseout events
    1. Triggered when mouse is moved on and off of an element
    2. Used to implement rollovers
      <script>
      // Cache images for quick response
      var imageOn = new Image();
      imageOn.src = "images/robotman_invert.png";
      var imageOff = new Image();
      imageOff.src = "images/robotman.png"
      
      function mouseOver(event) {
      	event.target.setAttribute("src", imageOn.src);	
      
      	// OR
      	// document.getElementById("robotman").src = imageOn.src;	
      }
      
      function mouseOut(event) {
      	event.target.setAttribute("src", imageOff.src);		
      	
      	// OR
      	// document.getElementById("robotman").src = imageOff.src;
      }
      
      function start() {
      	var img = document.getElementById("robotman");
      	img.addEventListener("mouseover", mouseOver);
      	img.addEventListener("mouseout", mouseOut);
      }
      
      addEventListener("DOMContentLoaded", start);
      </script>
      
      <img src="images/robotman.png" id="robotman" alt="Robotman">
      

      Robotman
      1. event is passed to event handlers which contains extra information about the event that fired
      2. event.target - element that received the event
  5. Other popular events (complete list)
    1. mousemove - triggered when the mouse is moved
    2. mouseup and mousedown - triggered when the mouse button is pressed and released
    3. keydown, keypress, keyup - triggered when the user is pressing, presses, and releases a key
    4. focus and blur - triggered when focus is given to or removed from a control
    5. submit and reset - triggered when a form's submit or reset button is pressed