Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to make a div into a link?

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='#';
})
like image 374
Chanckjh Avatar asked Jan 28 '13 10:01

Chanckjh


People also ask

How do you make a div a link?

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").

Can you make div boxes links?

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.

Can an entire div be a link?

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.


1 Answers

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; }
like image 166
Rory McCrossan Avatar answered Sep 17 '22 15:09

Rory McCrossan