Lab: JavaScript Timers and Events
Video
This lab has a ~25-minute video walkthrough that goes over the basic concepts, but which does not go through the solutions to every challenge. You can watch it on YouTube or download it to view later. Caption files will be available for download as well when they're edited (I'm currently waaay behind on this).
For this lab, it's probably better to watch the video before you work through it, or watch each part as you work through, because the video explains some stuff that might not be totally obvious from the lab itself, and it doesn't go through solutions in detail.
The video description on YouTube includes links to each part of the video if you're looking for a part that covers a specific task.
Download video | Download captions (coming soon)
Solutions
Overview
- Practice with JS functions
- Have some fun!
Setup
There is no starter code for this lab, but open a new empty document in Atom
and save it as pageControl.js
.
Modifying Page Appearance and Behavior
What kinds of changes can you make to the appearance or behavior of an existing website just by pasting code into the JavaScript console? It turns out that you can change a lot!
For most stuff that we change, simply refreshing the page will undo any changes, but there are browser extensions (like GreaseMonkey for Firefox) which let you load custom JavaScript every time you visit a page.
In this lab, we'll focus on code that will change the appearance or behavior of a website to break it or just to have fun.
Part 1: Appearance
Log onto your favorite social media page, or start with a common public page like www.google.com. Try a few of these ideas for changing the appearance of the page:
- Using the Javascript console, change the background color of the page.
- Next, try changing the background color or text color of a specific element.
- By setting the
display
value to"none"
, make part of the page, like a button, dissapear. - Can you rotate the page, or some part of it (maybe the logo)?
Hints:
- In Chrome, if you right-click an element in the inspector view, you can
chose Copy -> JS Path to copy a JavaScript expression to the clipboard that
will select an element. Then you can write
var element =
and paste to capture that element in a JavaScript variable. Note that these values aren't always stable when you refresh the page, unfortunately. - When changing styles, other style rules on the page may override yours. Try
adding "!important" to a property value at the end, like
font-family: fantasy !important
. - To transform the page, put a string into the
.style.transform
property of an element. These strings have specific effects, like'rotate(90deg)'
to rotate sideways.
Click here for instructions for selecting elements on www.google.com
To select the text input for search, which is the only text input on the page:
var search = document.querySelector('input[type="text"]');
To select the search button is harder, since for some reason there are two copies of it and the first one is invisible. Use this code:
var button = document.querySelectorAll('input[value="Google Search"]')[1];
Part 2: Setting Timers
There is a convenient function in JavaScript called window.setTimeout
which
allows us to set a timer and call a specific function after that timer runs
out. Try pasting the following code into the console on your target page:
function sayHi() {
alert("Hi!");
}
window.setTimeout(sayHi, 2000);
What happens immediately? What happens 2 seconds later?
The time value for setTimeout is given in milliseconds, so 1000 equals one second.
Looping Timers
Setting a timer to have something happen after a minute or two might be surprising, but we can do even better: we can write a function which sets a timer that triggers itself again, so that it will keep repeating forever.
Try this example (and refresh the page afterwards to get rid of it):
function annoying() {
alert("Hey!");
window.setTimeout(annoying, 1000);
}
// We have to call the function once to start the chain:
annoying();
Now try the following:
- Every 500 milliseconds, replace the search field contents on Google search with the string "hahaha".
Ping Pong
Even better than a constant loop, we can change something back and forth between two different states by having two functions that set up timers for each other. Try the following code in your console:
function nudgeUp(targetElement) {
targetElement.style.display="inline-block";
targetElement.style.marginTop = "0pt";
// This sets a timer to call nudgeDown with the same target element
window.setTimeout(nudgeDown, 1000, targetElement);
}
function nudgeDown(targetElement) {
targetElement.style.display="inline-block";
targetElement.style.marginTop = "24pt";
// This sets a timer to call nudgeUp
window.setTimeout(nudgeUp, 1000, targetElement);
}
// Call one of the functions with a certain target element to set off the chain
// Here imagine we used the code above to isolate the search button on
// www.google.com into a 'button' variable.
nudgeDown(button)
Important Note: quickly flashing colors can cause seizures or trigger headaches! You should never change too much of the screen too quickly using setTimeout! Keep your timeout values above 1500 if you are changing a lot of pixels, and don't change back and forth between bright and dark colors.
Try the following:
- Create two functions to change the rotation of an element so that it keeps wiggling back and forth.
Part 3: Events
We've used the onClick
attribute of buttons already to trigger JavaScript
code. As it turns out, there's a way to set this up directly within JavaScript,
with a function called addEventListener
. As a bonus, this method lets you
respond to lots of different events, not just clicks. Try pasting the following
code into the console:
function oops() {
document.body.innerHTML = "";
}
document.body.addEventListener("click", oops);
What happens when you click on the page? Why?
Other events that you can respond to include "mouseover"
and "keyup"
. See
the MDN Events reference
for more, especially under the "Keyboard events" and "Mouse events" categories.
Try the following:
- Create a function that adds a hyphen to Google Search's input box every
time the user types a character (using the
"keyup"
event trigger).
Your Own Custom Code
Combine the techniques above to create your own custom modification of your favorite website (you can make serious changes or silly ones). At the end of the lab, show your changes to another person or group and see if you can each figure out how the other's code works.
Some advanced ideas:
- Every 50 milliseconds, check the current time and set the rotation of something based on that so that it spins slowly.
- Set up a series of functions to make rainbow text.
- Change the font size randomly every time the user types a letter.
- When the user hovers over the search button, replace the contents of the
search text with the string
"This isn't what I meant to search for!"
- Change the top margin of a button whenever the mouse hovers over it so that it avoids the mouse. (If the margin is small, make it large, and if it's large, make it small).