facebook google plus twitter
Webucator's Free JavaScript Tutorial

Lesson: Images, Windows, and Timers

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

In this lesson, you will learn how to work with images, windows, and timers.

Lesson Goals

  • Learn to preload images.
  • Learn to create a slide show.
  • Learn to open and control a new window.
  • Learn to create timers.

Preloading Images

When using JavaScript to dynamically load an image, perhaps in response to some user interaction, preloading the image (the image not initially showing on the screen) can eliminate a delay in the image appearing for the user. Images can be preloaded by creating an Image object with JavaScript and assigning a value to the src of that Image. A sample is shown below:

Code Sample:

ImagesWindowsTimers/Demos/PreloadingImages.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Preloading Images</title>
<link href="style.css" rel="stylesheet">
<script>

var imagePaths = [];
imagePaths[0] = "Images/Hulk.jpg";
imagePaths[1] = "Images/Batman.jpg";

var imageCache = [];

for (var i=0; i<imagePaths.length; i++) {
	imageCache[i] = new Image();
	imageCache[i].src = imagePaths[i];
}

function imageRollover(img, imgSrc) {
	img.src = imgSrc;
}
</script>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover Function</h1>
<img name="Banner" src="Images/Banner.jpg"
	onmouseover="imageRollover(this, 'Images/Hulk.jpg');"
	onmouseout="imageRollover(this, 'Images/Banner.jpg');">
<img name="Bruce" src="Images/Bruce.jpg"
	onmouseover="imageRollover(this, 'Images/Batman.jpg');"
	onmouseout="imageRollover(this, 'Images/Bruce.jpg');">
<p>Who are you calling simple?</p>
</div>
</body>
</html>

Code Explanation

Notice that the code is not in a function. It starts working immediately as follows:

  1. An array called imagePaths is created to hold the paths to the images that need to be preloaded.
    var imagePaths = [];
  2. An array element is added for each image to be preloaded.
    imagePaths[0] = "Images/Hulk.jpg";
    imagePaths[1] = "Images/Batman.jpg";
  3. An array called imageCache is created to hold the Image objects that will hold the preloaded images.
    var imageCache = [];
  4. A for loop is used to create an Image object and load in an image for each image path in imagePaths.
    for (var i=0; i<imagePaths.length; i++) {
    	imageCache[i] = new Image();
    	imageCache[i].src = imagePaths[i];
    }

Windows

These days, popup windows are generally frowned upon; however, they can be useful in some cases. We'll look at a couple of examples, but first, let's see how to open a new window.

Syntax

var newWin = window.open(URL,name,features,replace);

All four parameters are options:

  1. URL - the URL of the page to load. If it is left blank, a blank window is open and can be written to with newWin.document.write().
  2. name - the target attribute of the window. This can be used to reuse an existing window if it is open.
  3. features - a comma-delimited list of window features. Some of the most common are:
    1. height - the height of the window
    2. width - the width of the window
    3. left - the left position of the window
    4. top - the top position of the window
    5. location - whether or not to include the location bar
    6. menubar - whether or not to include the menubar
    7. resizable - whether or not the window should be resizable
    8. scrollbars - whether or not to include scrollbars
    9. status - whether or not to include the status bar
    10. toolbar - whether or not to include the toolbar
  4. replace - true or false. If set to true, the new page replaces the current page (if there is one) in the browser window's history.

The height, width, left, and top features should be set in pixels.

The location, menubar, resizable, scrollbars, status, and toolbar features are boolean values: "true" or "false", "yes" or "no", or "1" or "0" will work.

The HTML5 specification advises browsers to ignore the features arguments completely, and some modern browsers do choose to ignore all but the size and positioning features.

The example below shows how to open a new window:

Code Sample:

ImagesWindowsTimers/Demos/window.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>New Window</title>
<script>
var eula;

function openWin() {
	eula = window.open("eula.html","eula","height=200,width=300,left=100,top=100");
	eula.focus();
}

function eulaChecked() {
	if (document.getElementById("confirmEula").checked && typeof eula == "undefined") {
		alert("Come on now.  Don't you think you should read the EULA first?");
		document.getElementById("confirmEula").checked = false;
		openWin();
	} else if (document.getElementById("confirmEula").checked && !eula.closed) {
		eula.close();
	} else if (!document.getElementById("confirmEula").checked) {
		openWin();	
	}
}
</script>
</head>
<body>
<form action="process.xyz">
<input type="checkbox" id="confirmEula" name="confirmEula" onclick="eulaChecked()"> Check to confirm that you agree with our <a href="eula.html" onclick="openWin(); return false;">user agreement</a>.
</form>
</body>
</html>

Code Explanation

Things to notice:

  1. We make eula a global variable so that we can access the window object from within multiple functions.
  2. In the openWin() function, we call eula.focus(); after opening the window. That's to bring the window to the foreground if it's already been opened.
  3. In the eulaChecked() function:
    1. We first check to see if the confirmEula check box has been checked before the EULA window has been opened (i.e., before a window object has been assigned to the eula variable). In this case, we scold the user and pop up the EULA window.
    2. We then check to see if the confirmEula check box has been checked and the EULA window is left open, in which case we close the EULA window via the window object's close() method.
    3. Finally, if the confirmEula check box has been unchecked, we pop the EULA window back open.

Timers

Timers are started and stopped with the following four methods of the windows object:

  1. setTimeout(code_to_execute,wait_time_in_milliseconds)
  2. clearTimeout(timer)
  3. setInterval(code_to_execute,interval_in_milliseconds)
  4. clearInterval(interval)

Let's take a look at how setTimeout() and clearTimeout() work first:

Code Sample:

ImagesWindowsTimers/Demos/Timer.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Timer</title>
<script>
	var timer;
	function changeBg(color) {
		timer = setTimeout(function() { document.body.style.backgroundColor=color; }, 1000);	
	}
	
	function stopTimer() {
		clearTimeout(timer);	
	}
</script>
</head>
<body>
<button onclick="changeBg('red')">Change Background to Red</button>
<button onclick="changeBg('white')">Change Background to White</button>
<button onclick="stopTimer()">Wait! Don't do it!</button>
</body>
</html>

Code Explanation

Things to notice:

  1. We make timer a global variable so that we can access the timer object from within multiple functions.
  2. In the changeBg() function, we create the timer. Note that we need to place document.body.style.backgroundColor=color in a function; otherwise, the code will execute immediately. In this case, we use an anonymous function, which works just like a regular function. Note that because the function is nested within the changeBg() function, it has access to the local variable color.
  3. The stopTimer() function simply clears the timer timer using clearTimeout().

The setInterval() and clearInterval() methods work the same way. The only difference is that the code gets executed repeatedly until the interval is cleared.

Popup Timed Slide Show

Duration: 15 to 25 minutes.

In this exercise, you will create a popup slideshow that runs by itself.

  1. Open ImagesWindowsTimers/Exercises/Timed-SlideShow.html in your editor.
  2. Add code to the startShow() function to pop up popup-show.html in a new 200px by 300px window. Make sure it comes to the foreground.
  3. Open ImagesWindowsTimers/Exercises/popup-show.html in your editor.
  4. Notice the play() function is called when the window loads. Add code to the play() function so that it changes the slide every second (1000 milliseconds).
  5. Add code to the stop() function to stop the slideshow.

Solution:

ImagesWindowsTimers/Solutions/Timed-SlideShow.html
---- C O D E   O M I T T E D ----

<script>
var showWin;

function startShow() {
	showWin = window.open("popup-show.html","showWin","height=300,width=200,left=300,top=100");
	showWin.focus();
}
</script>
---- C O D E   O M I T T E D ----

Solution:

ImagesWindowsTimers/Solutions/popup-show.html
---- C O D E   O M I T T E D ----
var showInterval;
function play() {
	showInterval = setInterval(function() { changeSlide(1); },1000);
}

function stop() {
	clearInterval(showInterval);
}
</script>
---- C O D E   O M I T T E D ----