Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make div clickable?

I want to make this div click-able and want to use same href of inside <a> and want to keep link in inside <a> also (so if JS is disabled then link will be accessible).

<div id="example">

<p> some text </p>

<img src="example.jpg />

<a href="http://stackoverflow.com"> link </link>

</div>

I mean i need like this.

<div id="example" href="http://stackoverflow.com">

<p> some text </p>

<img src="example.jpg />

<a href="http://stackoverflow.com"> link </link>

</div>
like image 336
Jitendra Vyas Avatar asked May 21 '10 03:05

Jitendra Vyas


People also ask

How do I make a div a hyperlink?

Create CSSSet the position to "absolute" for the inner <a> tag. Use the z-index property to place the link above all the other elements in the div.

How do I make a div a clickable link in HTML?

We simply add the onlcick event and add a location to it. Then, additionally and optionally, we add a cursor: pointer to indicate to the user the div is clickable. This will make the whole div clickable.

How do I make a div act like a button?

Adding role=“button” will make an element appear as a button control to a screen reader. This role can be used in combination with the aria-pressed attribute to create toggle buttons.


3 Answers

Something like this should do

$('#example').click(function() {
  window.location.href = $('a', this).attr('href');
});
like image 140
Ben Rowe Avatar answered Oct 06 '22 22:10

Ben Rowe


I cannot reply to the above conversation yet because I am new here, but I just wanted to say that you do not need to return false from this function. What that does is prevent the default behavior of the event from happening (which, in the case of clicking a div is nothing) and prevent the event from propagating up to the next element in the DOM hierarchy.

It is unlikely that either of these are necessary for this case. Additionally, if you do need these behaviors, you can get them separately and more clearly like so:

// note that the function will be passed an event object as
// its first argument.
$('#example').click(function(event) { 
  event.preventDefault(); // the first effect
  event.stopPropagation(); // the second

  window.location.href = $('a', this).attr('href');
});

Again, I don't think either approach is necessary in this case, but it is important to understand how they work, because you will need one or both of them frequently.

like image 33
Kent Avatar answered Oct 06 '22 22:10

Kent


<html>  
  <body>
    <div onclick="window.location.href = this.getElementsByTagName('a')[0].href;">
      <p>some text</p>      
      <a href="http://www.google.co.in/">link</a>
    </div>
  </body>
</html>
like image 2
vengatesh26 Avatar answered Oct 06 '22 20:10

vengatesh26