An image gallery: Block that click

  1. An image gallery
  2. Switch on click

Once you’re satisfied that the links work, add a script tag to the <head> of gallery.html.

<script type="text/javascript" src="gallery.js"></script>

Create a new, empty, script file called “gallery.js”, and in this file put:

function switchImage(link) {


return false;


This function will accept one argument: the link to the new image. For the moment, however, all the function will do is open an alert box displaying the URL to the image.

For each <a> tag in the HTML of gallery.html, add an onclick attribute with the value “return switchImage(this);”. For example, the first link’s line will look like this:

<li><a onclick="return switchImage(this);" href="gallery/Ancient_Sarcophagi.jpg">Ancient Sarcophagi</a></li>

Because switchImage returns false, the browser won’t follow the link.

Events in tags

In the previous example, we put an onclick into the document object using JavaScript. Here, we’re putting an onclick into the <a> tag using HTML.

Block that click: This

When inserting JavaScript into HTML tags, “this” is always the tag that the JavaScript has been inserted into. Here, “this” is the <a> tag object containing a link to Ancient_Sarcophagi.jpg.

  1. An image gallery
  2. Switch on click