What is the best practice for turning a div into a link?

I have a little problem here. I have a div with h1, h2 and p . I want to make a div into a link, but I can't just wrap a <a> around a div or h1, h2, p. This is not the right way, but what should I do to make the entire div into a link? Should I make each element in a span ? This will 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='#'; }) 
+6
source share
4 answers

Assuming your original HTML looks something like this, you should add a data parameter containing a link that will follow when you click on the div:

 <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 the click handler to the div :

 $('.link').click(function() { window.location.assign($(this).data('url')); }); 

Finally, be sure to add the cursor attribute in the CSS so that it is obvious that the div can be clicked:

 .link { cursor: pointer; } 
+5
source

You do not need JS or jQuery for this. An alternative would be to do something like this:

 <div> <a href="#"></a> <h1>Something</h1> <h2>Something else</h2> <p>Another something</p> </div> <style type="text/css"> div { position: relative; } div > a { display: block; position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 2; } </style> 

Of course, change the CSS selector so that they only affect what you want them to influence. The advantages of this, of course, if the user does not have JS enabled, he will still work fine, and better for SEO.

+8
source
 <div onclick="window.location = 'http://www.abc.com/';" style="cursor:pointer;"> </div> 
+2
source

To elaborate on what Rory suggested, I think it might be easier to use the actual link inside your div, as the user does not have javascript and search engine indexing.

 <div class="link"> <h1><a href="http://www.google.com">Heading One</a></h1> <h2>Heading Two</h2> <p>Paragraph</p> </div> 

Then find the h1 link and use this as url

 $('.link').on('click', function() { window.location = $(this).find('h1 a').attr('href'); }); 

And CSS

 .link { cursor:pointer; } 
0
source

All Articles