I've got a little issue here. I've got a div
with h1, h2 and p
. I want to make the div into a link, but I can't just wrap a <a>
around a div or h1, h2, p. That's not the correct way, but what should I do to make the whole div into a link?
Should I make every element into a span
? This would require a lot more work
<a href="#" class="link">
<span class="div">
<span class="h1"></span>
<span class="h2"></span>
<span class="p"></span>
</span>
</a>
or should I use javascript:
$('.link').click(function(){
document.location.href='#';
})
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").
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.
simple answer is no, you can use onclick with css cursor:pointer to get the same functionality, though. Show activity on this post. Per the HTML spec (HTML 4.01, Draft 5 and XHTML 1,1.1) an anchor tag <a> cannot enclose a <div> tag. Since this answer was posted, HTML5 has come out.
Assuming your original HTML looks something like the below, you should add a data
parameter containing the link to follow when the div is clicked:
<div class="link" data-url="http://www.google.com">
<span class="div">
<span class="h1"></span>
<span class="h2"></span>
<span class="p"></span>
</span>
</div>
Then you can attach a click
handler to the div
:
$('.link').click(function() {
window.location.assign($(this).data('url'));
});
Finally, make sure to add the cursor
attribute in CSS so it's obvious that the div is clickable:
.link { cursor: pointer; }
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