Javascript Tutorial 11 Events

HTML events are “things” that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can “react” on these events.

Here are some examples of HTML events:

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

Below are all the same:

<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
<button onclick="this.innerHTML = Date()">The time is?</button>
<button onclick="displayDate()">The time is?</button>

Javascript Tutorial 10 Scope

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have local scope: They can only be accessed within the function.

// code here can not use carName

function myFunction() {
    var carName = "Volvo";

    // code here can use carName

}

A variable declared outside a function, becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it.

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

myFunction();

// code here can use carName 

function myFunction() {
    carName = "Volvo";
}

Do NOT create global variables unless you intend to. In “Strict Mode” automatically global variables will fail.

In HTML, the global scope is the window object. All global variables belong to the window object.

var carName = "Volvo";
window.carName // "Volvo"

Javascript Tutorial 09 Objects

JavaScript objects are containers for named values called properties or methods. A method is actually a function definition stored as a property value.

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue",
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
};

You can access object properties in two ways:

objectName.propertyName
objectName["propertyName"]