How to make a clickable div

Making a clickable text or image is easy, just add the <a> tag surrounding it. But this doesn’t work with divs and sometimes we need a whole div to be clickable and not just text.
The following code is for JQuery but switching it to your favorite JS framework should be very easy.

First start by adding this to your div

<div class="clickable">
  <!-- DIV CONTENT --></div>

Now a little css to simulate the pointer on that div

.clickable:hover{ cursor:pointer; }

Now onto the JavaScript part

<script type="text/javascript"> 
$(document).ready(function()
{
	$("div.clickable").click(
	function()
	{
		window.location = $(this).attr("url");
		return false;
	});
 
});
</script>

You can use as many clickable divs as you want.

One Comment

  1. Joe Schmidt

    I am using this technique but noticed that if there is a link within the content of the div, and I click on said link, it takes me to wherever window.location = $(this).attr(“url”); tells it to go, not where the URL of the link is. Is there anyway around that?

Leave a Reply