November 17, 2009

IE, z-index, and making a DIV a link

By Fred Boyle

Recently I had the need to turn a DIV into a clickable link. This sounded like a fairly easy task until I got into it and ran into a few issues with Internet Explorer (IE). One of the challenges also was that I wanted to avoid using Javascript… I felt this needed to function without the need for Javascript. I’ve included a jQuery solution from Jeff Croft at the end of this post for reference.

Here’s the code I came up with to make things function:

<div class="project">
	<a href="/link/to/project" class="block-link">&nbsp;</a>
	<a href="/link/to/project"><img src="/img/project-thumb.jpg" alt="Thumb for project X" /></a>
	<h3><a href="/link/to/project">Project name</a></h3>
	<p>This project let use flex our design and code muscles to create a truly cool site.</p>
</div>
.project { position: relative; }
.project .block-link {
	display: block;
	text-indent: -9999px;
	position: absolute;
		top: 0;
		left: 0;
	width: 100%;
	height: 100%;
}

This gave me a nice DIV to hold my content while making the whole thing clickable. Things worked great in Safari and Firefox, however when I went to check in IE6 and IE7 life wasn’t so good. What ended up happening in IE was that my clickable overlay was underneath the image and text. Doing some searching on Google yielded various fixes to the problematic way IE handles z-index. No amount of z-index value changing or other variety of documented fixes were working in my situation.

So I started doing some trial and error research to see what might trigger a resolution. Because my clickable overlay was empty I thought content may help resolve the issue. I tested this theory and found that having a background color made things work as expected and as they behaved in the other browsers. Finally I was getting somewhere, so I ended up adding a transparent PNG background to the clickable overlay and all was good. So it seems IE doesn’t like DIVs lacking content to be above other elements, so faking content with a transparent background resolved the issue I encountered.

With this I can now nicely create an overlay for repeatable div elements that can occur on a listing page. I hope this helps some of you out there!

// Allow elements with the class “clickable“ to be, well, clickable.
// This basically emulates HTML 5 functionality that isn’t very well-supported yet. 
$(”.clickable“).click(function(event) {
	event.preventDefault(); window.location = $(this).attr(“href”);
});

Comments

There were no comments.

Post a Comment

commenting is disabled.