Order of execution

Your HTML page will be interpreted from top to bottom.





After that, it waits for things (events) to happen.
The browser/javascript allows you to specify code to run WHEN that event happens. The code is called event handlers
Notes

Events

There are many events that Javascript can capture. For a full list go to w3schools.

Mouse related events:
Event
onclick The user clicks on an element
oncontextmenu The user right-clicks on an element to open a context menu
ondblclick The user double-clicks on an element
onmousedown The user presses a mouse button over an element
onmouseenter The pointer is moved onto an element
onmouseleave The pointer is moved out of an element
onmousemove The pointer is moving while it is over an element
onmouseover The pointer is moved onto an element or onto one of its children



Keyboard related events:
Event
onkeydown The user is pressing a key
onkeypress The user presses a key
onkeyup The user releases a key



DOM object related events
Event
onerror An error occurs while loading an external file
onload An object has loaded
onresize The document view is resized
onscroll An element’s scrollbar is being scrolled



Form related events
Event
onblur An element loses focus
onchange The content, selection, or checked state has changed
onfocus An element gets focus
onreset A form is reset
onselect The user selects some text
onsubmit A form is submitted
Notes

Event Handlers

An event handler is a piece of code that runs when a specified event happens. There are several ways to add event handlers to your page.

Inline event handlers: Adding javascript code into the HTML Elements directly usually in the opening of that HTML element with the format below
  
<HTMLTAG eventname = "javascript code..."  >
So if we use the anchor tag as an example, it will look like this:
<a href="http://www.reed.edu/" onclick="alert('hello')"> Reed College </a>
Or something more familiar
  <button onclick="alert('ouch');"> click me </button>


Event Handlers as Properties of DOM Objects
Inline event handlers can get very messy. To separate form from function, you can assign event hanlders to selected objects in Javascript.

<button id="b1"> </button>

<script>
  var myButton = document.getElementById('b1');


  function clickResponse(){
       alert('you clicked me');
  }

  myButton.onclick = clickResponse;
</script>


There is an alternative way to do this without giving a function a name (in this case, clickResponse) and using that name. It is called anonymous functions.

<button id="b1"> </button>

<script>
  var myButton = document.getElementById('b1');
  myButton.onclick = function() {
       alert('you clicked me');
  }
</script>




All the methods we saw allows you to attach a single event handler to one event. If you attach a new event hanlder using those methods, it will overwrite the previous one.
With addEventListener() you can add multiple event handlers to a single event.

Unfortunately, this is very confusing but when using this method, do not use the "on" prefix. For example, use "click" instead of "onclick".
  var myButton = document.getElementById('b1');
  function sayHello() {
     alert('hello');
  }
  function sayBye() {
     alert('bye');
  }
  
  myButton.addEventListener('click', sayHello);
  myButton.addEventListener('click', sayBye);
 
Notes

Putting Javascript on the top of the page

Remember the order of execution from top to down?
 <html>
 <head>
 <script>
   var b = document.getElementById('b1');  
   b.innerHTML = "hello";    // THIS DOES NOT WORK!!!
 </script>
 <head>
 <body>
   <button id="b1"> click me </button>
 </body>
 </html>
 


If you run javascript after the window loads, then we won't have the problem of javascript not knowing about an HTML Element below it

Here, window is an DOM object is always available (you do not need to search for it in javascript). The onload event of window will fire when the browser finishes 'loading' the entire HTML page. This method allows you to put your javascript code at the top of the page, even if it depends on some HTML Element exisiting.
 <html>
 <head>
 <script>
   window.onload = function(){

    var b = document.getElementById('b1');  // this works because this runs after the page is loaded
    b.innerHTML = "hello";

   }
 </script>
 <head>
 <body>
   <button id="b1"> click me </button>
 </body>
 </html>
 
Notes

Event Object

Sometimes you would like to know more about the event that has been detected. For example, if a key has been pressed, which one? If a mouse has been clicked, where?

If you include an argument (e, or event, or anyname you'd liike) in the definition for the event handler function, javascript will automatically pass, what is known as the DOM event object. (For more information, see DOM Event Object) for the mouse. The event object gives you access to information related to the event.
<script>
  function where(event){
     // event object contains information regarding the event
     alert(event.offsetX + " " + event.offsetY); // location where the click event occured
  }
</script> 
    

<body onclick="where(event);">





Full Code for event object telling you which key has been pressed:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> The Title of this HTML Page </title>
<script>
window.onload = function(){
  var myInputField = document.getElementById("myinput");
  myInputField.style.width = "300px";

  function myFunction(e){
    var kc = e.keyCode;
    console.log(kc);
    if(kc == 27){ // Escape key
        alert("Possible Values for this field are... ");
      }
    if(kc == 65){ // 'a'
          alert("Possible Values for this field are... apple, air, auto");
      }
    } // end of function


    myInputField.addEventListener('keydown', myFunction);

}
</script>
</head>

<body>
This is the body of this HTML Page.
<input type="text" id="myinput">
</body>
</html>

Notes

Preventing Default Behavior

Using the event object, you can prevent the default behavior from happening. For example, the default behavior for clicking an anchor tag with a link is to go to that page. Well, you can prevent that like this using the preventDefault() method of the event object.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> The Title of this HTML Page </title>
<script>
window.onload = function(){
  var go = document.getElementById('a2');

  function refuseAccess(evt){
    alert("sorry, you are not allowed");
    evt.preventDefault();
  }


  go.addEventListener('click', refuseAccess);


}
</script>
</head>

<body>
<a href="http://www.google.com" id="a1"> Go to Google</a>
<br>
<a href="http://www.google.com" id="a2"> Do not go to Google</a>
</body>
</html>

Notes