How to make DIV clickable in areas without clicks?

I have a <div> that contains several links ( <a> tags) and other elements in it. I want the <div> to behave like a button, which means that every time the user clicks on each part of it, he must go to some link. There are several solutions like this: Make a div into a link I can make it work with jQuery too, however the problem is that I want the <a> tags in the <div> work as before. I could not find a solution that makes this possible. How can i do this?

+4
source share
2 answers
 $('#mydiv a').click(function(e) { e.stopPropagation(); }); 

Events are bubbling what they do. This is called distribution. Calling stopPropagation on a jQuery event object should prevent this event from swelling to your div that contains it.

jQuery docs here

And since the event handler does not return false , then the default processing for the browser using the <a> tags will still be started, which means that href is executed as usual.

Check out a working example here: http://jsfiddle.net/Squeegy/2phtM/

+3
source

I think you need an event handler that determines which element triggered the click - something like this

 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> $(function() { $("#links").click(handler); }) function handler(event) { var $target = $(event.target); if($target.is("#links")) { window.location = "divlocation.htm" } } </script> </head> <body> <div id="links" style="background: yellow"> <a href="test1.htm">link 1</a><br> <a href="test2.htm">link 2</a> </div> </body> </html> 
+1
source

Source: https://habr.com/ru/post/1391345/


All Articles