Tutorial :How to make div clickable?



Question:

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>  


Solution:1

Something like this should do

$('#example').click(function() {    window.location.href = $('a', this).attr('href');  });  


Solution:2

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.


Solution:3

<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>  


Solution:4

The above answers are all accepted by me. And generally u can make the same or even more great effect to "div" than "a" by css. And you can add js function to show the css changes when a event happened like Click. Maybe like this: DIV.onclick = function(){ change the target dom object css here }。 then when the event occurs, you will see the effect. and if you want to change href to another one. write js like location.href="http://www.target.com"; it will work for you.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »