JS Graffiti

JavaScript for Beginners

Class 4

Events

An 'event' is a type of object that is created when the user interacts with a web page.

For example, JS creates an event when a user clicks an element.


element.onclick = function () {
  //code to execute when the click happens
};
				

Types of Events

There are a variety of events. Some of the most common:

  • onclick: The event occurs when the user clicks on an element
  • onmouseover: The event occurs when the pointer is moved onto an element
  • onkeyup: The event occurs when the user releases a key
  • onload: The event occurs when a document has been loaded
  • onfocus: The event occurs when an element gets focus

Events and Code

How do you make an event trigger some code?

  1. Break your code into functions
  2. Associate a function with a JavaScript event

Calling Functions from HTML

You can call a function directly from your HTML code:


<button id="clickMe" onclick="sayHi()">Click Me!</button>
				

function sayHi() {
    alert ('Hi!');
}
				

Listening Functions

Listening functions work like many of the other things we have done. First, find the object:


var myTarget = document.getElementById('clickMe');
                

Then add an event to that object:


myTarget.onclick=function(){
     alert ('Hi!');
}
                

Practice

Download this week's sample code.

Make some JavaScript code fire after an onmouseover event. Try adding the event to the HTML and adding a listening function.

Preventing Defaults

Elements like buttons and links have default behaviors. However, the event objects has a built-in method to handle that:


element.onclick = function (event) {
  event.preventDefault();
};

				

This

The keyword this references the element that the user has just interacted with:


element.onmouseover = function (event) {
  console.log(this);
};

element.onclick = function (event) {
  this.style.backgroundColor = 'red';
  this.innerHTML = 'I've been clicked!';
};
				

Practice

Write code that targets this link:


<a href="http://girldevelopit.com/" id="gdiLink">Girl Develop It</a>
				

When a user clicks the link, the page should display an error message instead of going to the Girl Develop It homepage.

Forms

You can collect information from users to use in functions. The most common method is an HTML form:


<form id="temperatureForm">
    <label for="temp">Temperature:</label> <input type="text" id="temp" size="3"/> degrees in
    <input type="radio" name="tempFormat" value="F" checked />Fahrenheit
    <input type="radio" name="tempFormat" value="C" />Celsius <br />
    <label for="submitButton"></label> <input id="tempSubmitButton" type="submit" value="Submit" />
</form>
				

Retrieving Form Data

You retrieve the values of form elements using the value method:


var temperature = document.getElementById('temp').value;
console.log (temperature);
				

You can retrieve the value of a form at any time. Try onblur (when a form element loses focus).

Radio Buttons

Radio buttons usually do not have IDs, so you will need to use an array:


var radios = document.getElementsByName('tempFormat');

for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        var radioButtonValue = radios[i].value;
        // only one radio can be checked, so stop now
        break;
    }
}
				

Submit buttons

If you are going to retrieve form values with the submit button, be sure to prevent the default action!


var submitButton = document.getElementById('tempSubmitButton');
submitButton.onclick = function () {
    event.preventDefault();
    var temperature = document.getElementById('temp').value;
    console.log (temperature);
}

				

Practice

Collect a value from the input box on the page. Use it inside a function of some kind. For example, collect a number and multiply it by five or collect a name and display a greeting.

Timing Events

In JavaScript, it is possible to execute some code at specified time intervals.

  • setInterval() executes a function over and over again, at specified time intervals
  • setTimeout() executes a function, once, after waiting a specified number of milliseconds

setInterval

The syntax for setInterval() is:


setInterval(function, milliseconds);
				

For example, this is a simple clock:


var simpleClock = setInterval(myClock, 1000);
function myClock() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById('resultsBox').innerHTML = t;
}

				

clearInterval

You can use clearInterval() to stop a setInterval loop:


clearInterval(intervalVariable)
				

To stop our clock:


function myStopFunction() {
    clearInterval(simpleClock);
}

				

setTimeout

The method setTimeout() is similar, but it will only run once:


setTimeout(function, milliseconds);
				

For example, this code will wait 3 seconds, then create a popup box, unless the user triggers the clearTimeout():


var helloBox;
function sayHello() {
    helloBox = setTimeout(function(){alert('Hello')},3000);
}
function dontSayIt() {
    clearTimeout(helloBox);
}

				

Animations

By changing values slowly over time, we can create simple animations:


var targetPic = document.getElementById('turtlePic');
targetPic.onclick = function () {
    var leftMarginValue = 0;
    function increaseMargin() {
        leftMarginValue++  // update parameter each time
        targetPic.style.marginLeft = leftMarginValue + 'px' //set left margin
        if (leftMarginValue === 200)  // check finish condition {
            clearInterval(movePic);
        }
    var movePic = setInterval(function(){increaseMargin()}, 10) // update every 10ms
}

				

Practice

Using the function from the previous slide as a base, try changing some animation parameters. What happens?

Resources

  • JavaScript Guide, from the Mozilla Developers Network.
  • Codecademy, with interactive JavaScript lessons to help you review.
  • Udacity, javascript basics course online.
  • Code School, javascript part 1 tutorial.
  • Dash, free online tool for JS/HTML/CSS integration from General Assembly.