Grow your CSS skills. Land your dream job.

Last updated on:

Make Entire Div Clickable

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

Looks for a link inside div with class of "myBox". Redirects to that links value when anywhere in div is clicked.

Reference HTML:

<div class="myBox">
     blah blah blah.
    <a href="http://google.com">link</a>
</div>

Comments

  1. Permalink to comment#

    works very nicely. thanks.

  2. Permalink to comment#

    Chris, thanks for this. When I tried this it worked for a hover over empty space in the div but not for the link itself; when I clicked on the link itself it went to a 404 error. Any ideas?

    • Permalink to comment#

      It will make any div with the .myBox class clickable, so if there’s no link in one, it’ll 404, is that the problem?

  3. Very cool! Just right now I have used this in my project :D

  4. Very very nice.

    I had a job interview today. When asked if there were any blogs I read regularly, I mentioned css-tricks, and the interviewer said that was one of his faves, too.

  5. Nathan
    Permalink to comment#

    Great technique.
    What if you want to have other links inside the linked div? How would you keep those working still?

    • You could create a variable for the exact element that you want to target. Question is though, why would you want to do that? If you could control the dom just do it there. This is more for a last resort type deal like using it on something like Drupal Core links.

  6. this is very useful for my current project

  7. Once again, TOTALLY AWESOME!!!

  8. “window.location” seems not to work in IE if you are using RealURL. Any Ideas?

    Thx
    Christoph

  9. fixed it this way:

    var base = $j("base").attr("href"); 
    $j("#menu li a").each(function() { 
      $j(this).attr("href", base+$j(this).attr("href")); 
    });
    
  10. Tyler

    I think i am going to try this with tables…. Or is there an easier way?

  11. wow … very sweet idea :- )

    thanks

  12. Nice work
    really helpful

  13. There’s a pure CSS way to go about doing this. Just have an anchor (a) tag within the DIV that links to the URL you want. Then, set it to a block display, relative positioning, left and top equal to 0, width and height to full (or use jQuery to match all A’s within DIV’s to the same dimensions as the DIV).

    • Danny P

      Great Solution! This really helped.

    • Permalink to comment#

      Awesome… this helped me alot!

    • Permalink to comment#

      great tip but it should be absolute position not relative position.

      so set the div to relative position, and the “a” tag to
      display:block; absolute; top:0; left:0; width: 300px; height:200px;

    • Permalink to comment#

      Don’t listen to the person above me.
      They will make your ENTIRE page a link…

      Relative will make your “top:0; left:0;” relative to the DIV in which it’s contained, rather than absolute, which makes it top / left of the PAGE, not just DIV.

      You’re welcome :)

      This method works btw, but will interact differently depending on what other text / images / etc. you have in the same div, since it’s block display, so make sure you know what you want where prior to setting this up.

    • Malcolm
      Permalink to comment#

      Absolute positioning will be relative to the first parent element that has positioning set. In dan’s post he said to set the div’s position to relative and then make the link’s position absolute. This means that the top:0; left:0; will be referencing the containing div not the body of the page. If the position was not set on the parent div or any other ancestor elements, then it would take up the whole page as you pointed out.

      That being said I’m not sure if it is better to use absolute or relative positioning for the links, or if there is even a significant difference.

    • Michael’s answer is not entirely correct, and Malcolm did a good job of explaining why.

      I, too, am wondering whether absolute/relative positioning is even necessary here. I’ve successfully made entire divs clickable without messing with the positioning of the links. Hmmm I’ll have to look into this.

    • Tony
      Permalink to comment#

      I believe Dan’s answer to be correct, and sadly to float this over content out of the flow of text & images requires an absolute positioning (within a relative positioned parent element).

      Micheal’s comment appears to be confusing ‘absolute’ with ‘fixed’ which automatically uses the edge of the browser chrome for positioning.

      however support for css3 positioning is less reliable than the ubiquitous jQuery currently.

    • Permalink to comment#

      Yes. Yes yes yes. Delightful. Thanks, TerranRich.

  14. Derek
    Permalink to comment#

    This is awesome. I’ve been trying to figure out a better way to do this for a while.

    How can I ensure that the href title appears when I hover on the div and also that the URL appears in the status bar of the browser I’m using?

  15. El garch Hicham
    Permalink to comment#

    Very nice thanks :D

  16. Its much nicer this way and not having to wrap a whole div in an A tag.

    For usability (dependent on what you are using it for), remember to add cursor:pointer in your css. Nice simple bit of code thanks.

  17. Hi,

    I want to make entire div clickable, but my div is consisting of news ticker and each of then linked to different URL, will this solution work in these situation?

    Thanks,
    Dearthelusion

  18. l3v1tcl30s
    Permalink to comment#

    oops, didn’t mean that to be a direct reply =]

    I’m new to scripting in jQuery. How would I set the target to be a new window?

    Any help would be greatly appreciated!

  19. Mdbx
    Permalink to comment#

    @l3v1tcl30s

    $(function() {
      $("a").attr("target","_blank");
    });
    • Mike
      Permalink to comment#

      So how do you combine that with Chris’ code? I’ve tried all sorts of combinations, like:

      window.location=$(this).find("a").attr("href").attr("target","_blank");

      but I can’t get it to work

    • whitecreek
      Permalink to comment#

      This is not working:

      $(function() {
        $(".myBox a").attr("target","_blank");
      });
      
      $(".myBox").click(function(){
           window.location=$(this).find("a").attr("href"); 
           return false;
      });
      

      As Mike was asking, Anyway to add target=”_blank” to roy post original jquery code?

      Thanks in advance.

  20. henk
    Permalink to comment#

    This doesn’t seem to work with IE 8.0. Is that correct?

  21. Permalink to comment#

    if the div consist of more than 1 hyperlink. which url will the jquery reads

  22. Josh
    Permalink to comment#

    Yeh roy! Thanks!

  23. Permalink to comment#

    Quick and lightweight, thanks! You can also wrap an bunch of elements in “a” tags, and this is semantic HTML5 markup. But it’ve had issues with that in older browsers. If you were to go that route make sure all the elements inside the “a” are inline by default (like a span or p), if necessary you can change them to display: block in the CSS.

    Chris’ method seems a little cleaner tho ;)

  24. Permalink to comment#

    Oh, thanks! It’s the solution I’ve beem looking for!

  25. ray van
    Permalink to comment#

    Nice tricks Thanks!

  26. John Steelman
    Permalink to comment#

    Why not just do this:

    
      <div  onclick="location.href='webpage.html;" >
        [.... anything you want ...]
     </div>
    
  27. Seems like this is an old thread, but hey it was still useful to me!
    Also, thanks to the person above me (John), I actually used your solution.
    Regards

  28. Permalink to comment#

    What would be the best practice to apply this into a Joomla! Website?

  29. I found this method and I wanted to share it with you guys because I found it to be just want I needed for a DIV that contains more then one link:

    
    <script type="text/javascript">
    $(document).ready(function(){
       var block = $("MyDIV");
       block.click(function(){
          window.location = $(this).find("a:first").attr("href")
       });
       block.addClass("clickable");
       block.hover(function(){
          window.status = $(this).find(".a:first").attr("href")
       }, function(){
          window.status = ""
       })
    });
    </script>
    

    You can even use this for more then one div if the window.location is the same for both of them like this:

    
    <script type="text/javascript">
    $(document).ready(function(){
       var block = $("MyDIV1, MyDIV2, MyDIV3");
       block.click(function(){
          window.location = $(this).find("a:first").attr("href")
       });
       block.addClass("clickable");
       block.hover(function(){
          window.status = $(this).find(".a:first").attr("href")
       }, function(){
          window.status = ""
       })
    });
    </script>
    
  30. Cool solution, but in case someone is googling around for a solution (like I was today), I found a thread over in stackoverflow for a solution sans js:

    http://stackoverflow.com/questions/796087/make-a-div-into-a-link

    For those looking for valid HTML way without javascript.

    cheers!

  31. Valen

    The solution gets even simpler…no need for jquery sizing or any of that business:

    div {
    position: relative;
    }

    a {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    }

    • lucas
      Permalink to comment#

      Or by inserting the following within your div tag:

      onclick=”location.href=’http://www.example.com';” style=”cursor:pointer;

  32. For those using HTML 5 you can now wrap any block-level element in an A tag:

    <a href=”#”>
       &ltdiv>
          blah blah blah
       &lt/div>
    &lt/a>

    And for hover state just add a class to your div, and then add a css class .whatever:hover {}.

  33. thom

    This is a javascript trick…not a CSS trick.

  34. thanks man, this works like magic

  35. hi there it is what I got to get 2 div with images bg clickable
    I am just looking for the solution to get it open in a new window target:”_blank”

    can someone help me on this as the info up above are not working for me

    var Page = {
    mouse:{x:0,y:0},
    start:function() {
    $j(“.mblock, .social”).bind(“click”,function(evt) {
    if ($j(this).attr(“href”)) {
    window.location = $j(this).attr(“href”) ;
    }
    }) ;
    }
    } ;
    var $j = jQuery.noConflict() ;
    $j(document).ready(Page.start) ;

    • oups

      
      	
      		var Page = {
      			mouse:{x:0,y:0},
      			start:function() {
      				$j(".mblock, .social").bind("click",function(evt) {
      					if ($j(this).attr("href")) {
      						window.location = $j(this).attr("href") ;
      					}
      				}) ;
      			}
      		} ;
      		var $j = jQuery.noConflict() ;
      		$j(document).ready(Page.start) ;		
      		
      	
  36. Chuck Ezuma
    Permalink to comment#

    I’m sorry, but any solution that involves javascript is complete overkill. This can be accomplished quite simply using HTML and CSS alone:

    HTML CODE:

    <a href="#" rel="nofollow">

    CSS CODE:

    a.yourClass{
          display:block;
          width:'';
          height:'';
    }

    Just specify the width and height of the clickable area.

    Less lines of code is always better.

    I use javascript only when necessary. Remember that 3% of users have it disabled on their browsers.

    • lucas
      Permalink to comment#

      Or you can simply add this inside your div tag:

      onclick=”location.href=’http://www.example.com';” style=”cursor:pointer;

      Fewest lines as possible!

  37. whitecreek
    Permalink to comment#

    Hi,

    Anyway to add target=”_blank” to this:

    
    $(".myBox").click(function(){
         window.location=$(this).find("a").attr("href"); 
         return false;
    });

    Simply adding:

    
    $(function() {
      $(".myBox a").attr("target","_blank");
    });

    as a new function within the jquery chunk is not working for me.

    Thanks in advance.

  38. Permalink to comment#

    This is really cool. But how to make whole not clickable.

  39. lucas
    Permalink to comment#

    Here is a much easier way:

    Insert this within the DIV tag that you want to make linkable:

    onclick=”location.href=’http://www.example.com';” style=”cursor:pointer;

    That’s all you have to do.

  40. Permalink to comment#

    Thanks Chris, I just used this on the homepage of my site and added:

    .myBox { cursor: hand; cursor: pointer; }

    to force a hand cursor when rolling over the .

  41. Matt
    Permalink to comment#

    Out of interest, why not just use jQuery to trigger the click event on the link?

    <div class="myBox">
         blah blah blah.
         <a href="http://google.com" target="_blank">link</a>
    </div>
    $('.myBox').click(function(){
        $(this).find('a').trigger('click');
    });
    
  42. Permalink to comment#

    To make the link open in a new window/new tab, use the following code:

    $(".myBox").click(function(){
        window.open($(this).find("a").attr("href"));
        return false;
    });
    
  43. Permalink to comment#

    After many answers on many sites including stackoverflow, this thread actually had working solutions. Thanks to all.

  44. Peter
    Permalink to comment#

    I’ve got a clickable div. With the HTML5 data- attribute I declare the link
    f.e. <div class=”item” data-href=”LINK”></div>

    In this div there is a link. If I click the link the page go to the data-href link.
    But can you trigger that if you click the link in the text that you don’t go to the link that is specified in the data-href?

    example on jsfiddle

  45. Adam
    Permalink to comment#

    The javascript is a bit of an overkill… An easier solution would be to wrap the div in a “link” with a display:block style

    <a style="display:block" href="http://css-tricks.com">
      <div>My div contents</div>
    </a>
    
    

    Then style your CSS to remove the underline or whatever.. Hope this helps.. :)

  46. It works, but it’s very bad for SEO. The method of Adam is way better.

    • whitecreek
      Permalink to comment#

      Better if you don’t have to worry about IExplorer8 and lower, and even better if you remove the inline css rule…

  47. Permalink to comment#

    you can add functionality to this to allow you to insert subsequent links from the first by inserting and else statement and inserting this:
    else{
    window.location=e.attr(“href”);
    }

  48. Giancarlo
    Permalink to comment#

    Can’t recall where I found this or I’d give credit, but this is what works for me.

    div
    {
    position: relative;
    }

     a {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        text-decoration: none; /* Makes sure the link   doesn't get underlined */
        z-index: 10; /* raises anchor tag above everything else in div */
        background-color: white; /*workaround to make clickable in IE */
        opacity: 0; /*workaround to make clickable in IE */
        filter: alpha(opacity=1); /*workaround to make clickable in IE */
    }
    
  49. Tony
    Permalink to comment#

    Nice Giancarlo,

    Unfortunately, doesnt that prevent me from making a background color change on hover?

    I’ve read through all of the above. What’s the verdict that works in IE7 and above and allows a background color change on hover? I’m confused. The original doesn’t?

  50. Permalink to comment#

    Nice trick, but we can simplified to this:

    
    

    jQuery:

    $('#click-div').click(function() {
        window.location = $(this).attr("data-href");
        return false;
    });
    

    The above will create a square click-able div, the only annoying think here is if you clicked on it, on the location bar you will see # added to the end of address, to get over this, replace # in data-href attribute of the div with javascript:;. Tested on FireFox 19.

  51. Simone

    Great! Fast and clean solution!

  52. Nick

    Hey
    I get an error when using this in my wordpress theme, any suggestions?

    unexpected ‘(‘, expecting variable (T_VARIABLE) or ‘$’

  53. Liz

    In my case I require the function validates whether links are external or not. This what I use. Works fine

    $(".clickablebox").click(function() {
        var thislink = $(this).find("a");
        if ( thislink.attr('target') == '_blank') 
            window.open(thislink.attr("href"));
        else
          window.location=thislink.attr("href");
        return false;
    });
    
  54. Ahmed

    That is astounding, using such a simple technique to get great results.

  55. Permalink to comment#

    This is a simple question I suppose. Say I’m using this to convert a number of equally named divs with this function and I want to turn one of them off if a certain image attribute exists. How would I remove this from a single div?

    if ($('img').attr('instoreonly') !== undefined) {
                /*I want to remove this from a specific div as defind above. */         
        } else {
            $(".four-up-wrap").click(function () {
                        window.location = $(this).find("a").attr("href");
                        return false;
                });             
    }   
    

    Thanks!

  56. Alex
    Permalink to comment#

    I LOVE CSS-TRICKSDOTCOM!!!

  57. Alex K.
    Permalink to comment#

    Very nice! Works like a charm!!

  58. James Robertson
    Permalink to comment#

    But using target “_blank” – its not working

    Any ideas?

    Cheers

  59. James Robertson
    Permalink to comment#

    sorry I think you got the wrong end of the stick.

    Its an small symbol image – Hopefully this can open on another page when clicked.

    The click is working – fine

  60. Permalink to comment#

    For opening the link in the new window, instead of going with window.location = someurl say window.open([someurl])

  61. thanks for this beautiful idea and nice trick.

    I have one question, I hope your can solve this as well.
    I am using CPC network ads on my website as publisher.
    normally these website give you script to be placed inside the .
    I have placed the code like this
    <div class="someclass"> <script type="text/javascript" src="URL"></script></div>

    Every time page is loaded a new URL is generated for the add.
    I want to capture that URL and store it in a NEW-LINK

    <a href="NEW-LINK"> LINK </a>

    so that when i click this NEW-LINK , then it clicks the URL generated by the CPC script.

    I have tried using iframes, but to no avail.

    Thanks for your support

  62. kgarske
    Permalink to comment#

    years later and still helping out.
    thanks for this beautiful idea and nice trick.

  63. Hi
    I have created a clickable div tag,by Just using a piece of CSS code and no Javascript!
    here is the solution:

    http://jsfiddle.net/chriscoyier/y7L9D/

  64. You would need

    onClick="window.open('http://www.teamvalleylinks.com/')"
  65. hettomei
    Permalink to comment#

    Because every body put their code :)
    here is my solution :

    // Bind every new and future element wich have a data-click-url
    $(function() {
      $(document).on("click", "[data-click-url]", function(event){
        event.preventDefault();
        window.location=this.getAttribute('data-click-url');
        return false;
      });
    });
    
    Lorem ipsum ....
    
  66. Permalink to comment#

    Awesome snippet. I’ve modified it just slightly to support opening in a new or the same tab depending on your HTML.

    $(".click-box").click(function(){
        window.open( $(this).find("a.box-link").attr("href"), $(this).find("a.box-link").attr("target") );
        return false;
    });
    

    After that, all you have to do is add the click-box class to your div, and include the link with the box-link class. Then you can set your target as _self or _blank depending on how you want that link to behave.

  67. Pooja
    Permalink to comment#

    Other one is add onclick=”location.href=’#';” style=”cursor: pointer in DIV

  68. lol. didn’t use markdown

    <a href=”blah”><div>blah blah blah</div></a>

  69. James Robertson
    Permalink to comment#

    Please have a look

    http://www.jrdesign-website.co.uk/battle_zone_laser/contact_us.html

    When you are on the contact page – scroll down to the green bus / cycle symbols)

    The clicks are working on the symbols

    but not opening in a new page. Any ideas?

  70. You would need (sorry for double post)

    onClick=”window.open(‘http://www.teamvalleylinks.com/’)”

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".