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
};
There are a variety of events. Some of the most common:
How do you make an event trigger some code?
You can call a function directly from your HTML code:
<button id="clickMe" onclick="sayHi()">Click Me!</button>
function sayHi() {
alert ('Hi!');
}
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!');
}
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.
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();
};
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!';
};
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.
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>
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 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;
}
}
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);
}
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.
In JavaScript, it is possible to execute some code at specified time intervals.
setInterval()
executes a function over and over again, at specified time intervalssetTimeout()
executes a function, once, after waiting a specified number of millisecondsThe 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;
}
You can use clearInterval()
to stop a setInterval loop:
clearInterval(intervalVariable)
To stop our clock:
function myStopFunction() {
clearInterval(simpleClock);
}
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);
}
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
}
Using the function from the previous slide as a base, try changing some animation parameters. What happens?