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 variety of events. Some of the most common:
onclick
: The event occurs when the user clicks on an elementonmouseover
: The event occurs when the pointer is moved onto an elementonkeyup
: The event occurs when the user releases a keyonload
: The event occurs when a document has been loadedonfocus
: The event occurs when an element gets focusHow 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 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 a default behaviors. However, the event
object 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; i < radios.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) {
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, 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?
Pick your favorite safari animal and create an object. Assign at least two properties and two methods to your animal object. Make at least one method something that involves moving - walking, running, swimming, etc. Then, build a web page that:
Please take a moment before you leave class today to answer a couple quick questions about class.
We strive to make every GDI class better than the last and your ideas help us do that.