I have a <div>
which contains a few links (<a>
tags) and other elements in it. I want to have the <div>
behave like a button, which means whenever the user clicks on every part of it, it should navigate to some link. There are a few solutions like this one:
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>
to work like before. I couldn't find any solution which makes this possible. How can I do this?
If you absolutely need to use JavaScript, one way is to find a link inside the div and go to its href when the div is clicked. This is with jQuery: $(". myBox").
How do you make a CSS element not clickable? To make a link unclickable using CSS, you can use the pointer-events property. pointer-events: none; on the link that you want to make unclickable and it will not let you click the link.
You can't make the div a link itself, but you can make an <a> tag act as a block , the same behaviour a <div> has. You can then set the width and height on it. However, this doesn't make a 'div' into a link. It makes a link into a block element.
$('#mydiv a').click(function(e) {
e.stopPropagation();
});
Events bubble up, that's what they do. This is called propagation. Calling stopPropagation
on the jQuery event object should prevent that event from bubbling up to your div that contains it.
jQuery Docs here
And since the event handler does not return false
, then the browser default click handling for <a>
tags will still be fired, which means the href
is followed as normal.
Check out a working example here: http://jsfiddle.net/Squeegy/2phtM/
I think you need an event handler which 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With