tags:

views:

93

answers:

2

I have a link inside a div and I need to make the whole div clickable... found several tutorials on the Internet but non of them worked for me...

Can anyone please help?

+7  A: 

Raw JavaScript:

<div onclick="alert('You clicked me !')">Click Me</div>

jQuery:

$('#div_id').click(function(){
  alert('Clicked !!');
});

Update: (With reference to your link)

<div class="myBox">
     blah blah blah.
    <a href="http://google.com"&gt;link&lt;/a&gt;
</div>

jQuery:

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

The above code cancels the default action of link (going to link) with return false and binds the click event to the div with class myBox, then it finds the link's src attribute inside the div and window.location is used to redirect the page to the src attribute of the link present inside the div. So this basically makes the div clickable.

Sarfraz
+3  A: 

If you're saying you want the entire div to be clickable for navigation, then you can either wrap it with an anchor () tag, which is not standards compliant, or add a css style to the contained anchor tag, making it the size of the containing div, which is standards compliant. I will use a div that is 250px by 250px in this example:

<div id="container"><a href="" style="display:block;width:250px;height:250px;">Link</a></div>
Allen Gingrich
This is just what I was looking for. Thanks!!!
Levani
Why is it not standards compliant to have a `div` within an `a`? Is there a useful resource somewhere that dictates which elements can reside in which (I realize that block-level within inline is incorrect, but...)?
Eric
You cannot have a block display element contained in an inline element. That's right. It won't break your code in browsers, but it most likely will not validate correctly.Glad I could help, Levani.
Allen Gingrich