Highlight Last Clicked Element

A forum question about returning the id of the element that was last clicked on (something rather pointless since you already have a direct reference to that element in the DOM and so don't need it's id in order to be able to reference it for subsequent processing) got me thinking about whether there would be any variant on the script that person was trying to build that would actually serve some purpose. The conclusion that I reached was that while simply returning the element itself rather than the id is the easiest way to allow subsequent processing of the element that actually setting an id on the element (after removing it from whatever element it might have been on before) might actually be useful in some circumstances.

The following is an actual example of where setting an id on the element that was clicked on actually does something. In this instance we have a number of images inside of a div. The div has an id so we can attach an event handler or listener to it to handle when any of the content of the div is clicked on. The function that the handler or listener calls attaches a specific id to the specific tag within the div that was last clicked on and that id stays attached to that element until the next click event occurs. With some appropriate CSS using the id we can have a the last element clicked on styled differently to all the others - in this case the CSS used changes the background colour that is displayed as padding around the images.

Here's the relevant part of the CSS I used for the above example:

#thumbnails {background-color:#ccc;}
#thumbnails img {padding:20px;}
#lastclicked {background-color:#cc0;}

Hre's a section of the HTML (note that only the div wrapping the content needs an id and we can have as many tags inside of the div as we like and the script will work for all of them):

<div id="thumbnails">
<img src="thumb1.jpg">
<img src="thumb2.jpg">

Finally here's the JavaScript function that we need to attach either as an event handler or less obtrusively as an event listener to the div:

... = function(event) {
var x, elem;
x = document.getElementById('lastclicked');
if (x) x.id = null;
elem = event.srcElement || event.target;
elem.id = 'lastclicked';

For an event handler simply substitute document.getElementById('thumbnails').onclick for the ... or for an event listener substitute a function name for the ... and include that as the second parameter of the addEventListener call (andr attachEvent if you are still catering for IE 8 users).


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow