tags:

views:

990

answers:

7

How do you make a div tag into a link. I would like my entire div to be clickable.

A: 
<div style="cursor:pointer;" onclick="document.location='http://www.google.com'"&gt;Foo&lt;/div&gt;
Rob
+2  A: 

JS:

<div onclick="location.href='url'">content</div>

jQuery:

$("div").click(function(){
   window.location=$(this).find("a").attr("href"); return false;
});

Make sure to use cursor:pointer for these DIVs

Nimbuz
If I didn't understand the jQuery sample wrongly, the HTML have to be structured this way: <div><a href="yourlinkhere">Your link text</a></div>
Seh Hui 'Felix' Leong
Yes, and thats probably a better way to do it. I just posted it as an alternative.
Nimbuz
A: 

You can make the entire DIV function as a link by adding an onclick="window.location='TARGET URL'" and by setting its style to "cursor:pointer". But it's often a bad idea to do this because search engines won't be able to follow the resulting link, readers won't be able to open in tabs or copy the link location, etc. Instead, you can create a regular anchor tag and then set its style to display:block , and then style this as you would a DIV.

Ben
A: 
<div onclick="document.location='http://www.google.com'"&gt;Content Goes Here</div>
Ryan Michela
+6  A: 

DON'T DO IT.

  • If you wants a link, wraps the content in a proper <A>NCHOR</a>.
  • If you wants to turns the <DIV> into a link, use "Javascript" to wraps the <DIV> inside an <A>NCHOR</A>
  • If you want to perform some actions on clicking the <DIV> use the onclick event handler. And don't call it a "link".

...

chakrit
A: 

You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:

$('div#id').click(function (e) {
  // Do whatever you want
});

This solution has the distinct advantage of keeping the logic not in your markup.

James Thompson
+2  A: 

If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.

As such:

<div style="height: 80px"><a href="#" style="display: block">Text</a></div>

Now when the user floats their cursor in that div the anchor tag will fill the div.

jtyost2
In Firefox 3.5 and IE8, I have to add "height: 100%;" to the anchor tag for it to take up the whole DIV height. Great alternative to the Javascript solutions.
Seh Hui 'Felix' Leong