tomasdev

web development handcrafted

DIV click event without JS

15 Jun, 2009. Written by Tom Roggero

So, the thing is a really usability concept. Most of us have been working with a div, and to make entire div a clickable box, through javascript assign the onclick event and css pointer cursor. But today you will learn a really interesting thing, without javascript and really much usable than that one. And is working with IE.
So before you had used something like:

 
<script type="text/javascript">
	$('#item').css("cursor", "pointer").click(function(){
		// do something like
		window.location = 'somepage.html';
	});
</script>
<div id="item">
 
Some text
<ul>
<li>Some</li>
<li>List</li>
<li>Items</li>
</ul>
 
	<img src="some-image.gif" alt="Some image too" />
</div>
 

If you are a little dumb, like me, you might had tried:

 
<a href="gothere.html">
<div>content goes here</div>
 
</a>
 

But that is not W3 valid! Anyway it doesn't work fine.
NOT ANYMORE!! With that example you might see everything goes OK, but what about SEO? what about javascript-disabled browser? Also, what about "third click" on Firefox? (I mean to open it in a new tab like clicking the scrollwheel)
You can use my pretty fix without any piece of javascript. Just using CSS + HTML (valid!)

 
<div class="mybox">
	<a href="gothere.html" class="makeit"></a>
 
Some text for a paragraph
<ul>
<li>Some</li>
<li>List</li>
<li>working</li>
<li>linked items</li>
</ul>
</div>
 

Which is really valid content. And set in your CSS

 
.mybox{
	/* add your style */
	background:#fff;
	padding: 10px;
	/* but dont forget next lines */
	position:relative;
	width:200px;
	height:200px;
}
.mybox .makeit{
	background-image: url(fake_image.gif); /* fake_image doesnt have to exist, this is a fix for IE */
	display: block;
	height: 100%;
	position: absolute;
	margin: -10px; /* some negative margins if you are using padding in .mybox */
	width: 100%;
	z-index: 10;
}
 

Simple huh? And that is working properly like it must do. Awesomeness. Feel free to comment if you need help with this piece of code

5 Comments /

Vijay
14/09/2009

WoW!! that is awesome….ppl like u can make our world evolve.

thanks a lot for the tut……!!

Becky
09/07/2010

I am have trouble getting this to work in IE7, half of the div is linking and the other half is not. Any ideas?

Tomas
15/07/2010

@Becky
Are you using paddings or margins on the div?
Is div height fixed?

glixtulty
01/04/2011

Please ease me to create collection

Leave a Reply