How to make div interactive?

I want to make this div accessible and want to use the same href inside <a> and also want to keep in touch inside <a> (so if JS is disabled, the link will be available).

 <div id="example"> <p> some text </p> <img src="example.jpg /> <a href="http://stackoverflow.com"> link </link> </div> 

I mean, I need it like that.

 <div id="example" href="http://stackoverflow.com"> <p> some text </p> <img src="example.jpg /> <a href="http://stackoverflow.com"> link </link> </div> 
+7
javascript jquery css xhtml
source share
4 answers

Something like this should

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

I cannot answer 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. This prevents accidental behavior of the default event (which does not matter when the div button is pressed) and prevents the event from propagating to the next element in the DOM hierarchy.

It is unlikely that any of these factors would be necessary for this case. In addition, if you need this behavior, you can get them separately and more clearly:

 // 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 do not think that in this case any approach is necessary, but it is important to understand how they work, because you will need one or both of them often.

+3
source share
 <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> 
+2
source share

The above answers are accepted by me. In general, you can do the same or even more the effect of “div” than “a” css. And you can add a js function to show css changes when an event like Click occurs. Maybe like this: DIV.onclick = function () {change the dom css target here}, and then when the event happens, you will see the effect. and if you want to change href to another. write js as location.href = "http://www.target.com"; It will work for you.

0
source share

All Articles