I decided to develop something like that in jQuery. Here it is for you to download! Let's take a look at the HTML code first.
<h2>Crane fly</h2> <div class="photo"> <div class="title"> <strong>Crane fly</strong> </div> <div class="aroundImage" style="height: 534px;"> <div class="warning"> <a href="javascript:void(0)">Click here to view this image.</a> </div> <img src="images/macro03.jpg" alt="Crane fly - Macro Work" class="hidden" /> </div> <div class="description"> This is a <em>tipula oleracea</em>. Its wingspan can reach 6cm! </div> </div>What that does is it displays a black square where the photo should be, with a warning. It has the height put in explicitly to reflect the size of the picture. If the user clicks anywhere on the black square (not necessarily the warning message), the photo will appear. Now, the interesting bit, the jQuery bit.
$(function() { // This will run on windows onload. $('div.warning a').bind('click', function(event) { var $aroundImage = $(event.target).closest('div.aroundImage').click(); }); $('div.aroundImage').bind('click', function(event) { var $aroundImage = $(event.target); var $hiddenImage = $aroundImage.children('img'); var $warningMessage = $aroundImage.children('div.warning'); $hiddenImage.show(); $warningMessage.hide(); $aroundImage.css('cursor', 'default'); }); });OK, let's describe it step by step. The whole thing is wrapped in this:
$(function() { // This will run on windows onload. // ... });The dollar sign ($) is obviously jQuery. By passing it a function like that we make sure that the function will run when the HTML document is loaded, i.e. when all page elements are available. What is worth mentioning, you can make the call many times and all of the given functions will run when body is loaded in the order they are declared.
$(function() {/* ... */}); $(function() {/* ... */}); $(function() {/* ... */});Let's now take a look at this.
$('div.aroundImage').bind('click', function(event) { var $aroundImage = $(event.target); var $hiddenImage = $aroundImage.children('img'); var $warningMessage = $aroundImage.children('div.warning'); $hiddenImage.show(); $warningMessage.hide(); $aroundImage.css('cursor', 'default'); });Here we use jQuery bind function to bind an event, which is a jQuery preferred way of event handling free from browser inconsistencies. We then obtain the hidden image to show it and the warning message to hide it. We also change the cursor to the default one (from pointer) because there is nothing else to click on. Here we redirect warning message onclick event to the div onclick event to avoid duplicating code.
$('div.warning a').bind('click', function(event) { var $aroundImage = $(event.target).closest('div.aroundImage').click(); });What is good about this jQuery code is that it doesn't care how many hidden images you have on the page. And the images don't need to have unique IDs or anything like that.