Make Entire Div Clickable

Update: this probably isn't a thing you need to rely on JavaScript for anymore. Since HTML5, this is perfectly valid:

<a href="http://example.com">
  <div>
     anything
  </div>
</a>

And remember you can make links display: block; so sometimes you don't even need the div.

But if you absolutely need to use JavaScript, one way is to find a link inside the div and go to it's href when the div is clicked.

$(".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>

Or, you could set a data-attribute on the div and do like:

window.location = $(this).data("location");

Comments

  1. User Avatar
    Dyllon
    Permalink to comment#

    works very nicely. thanks.

  2. User Avatar
    Nathan
    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?

    • User Avatar
      Ian
      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. User Avatar
    Bob Hay
    Permalink to comment#

    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.

  4. User Avatar
    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?

    • User Avatar
      Riad Kilani
      Permalink to comment#

      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.

  5. User Avatar
    xRommelx

    this is very useful for my current project

  6. User Avatar
    Christoph

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

    Thx
    Christoph

  7. User Avatar
    Christoph

    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")); 
    });
    
  8. User Avatar
    Tyler

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

  9. User Avatar
    Artur Ejsmont
    Permalink to comment#

    wow … very sweet idea :- )

    thanks

  10. User Avatar
    Edwin
    Permalink to comment#

    Nice work
    really helpful

  11. User Avatar
    TerranRich
    Permalink to comment#

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

    • User Avatar
      Danny P

      Great Solution! This really helped.

    • User Avatar
      Thomas
      Permalink to comment#

      Awesome… this helped me alot!

    • User Avatar
      dan
      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;

    • User Avatar
      Michael
      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.

    • User Avatar
      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.

    • User Avatar
      Kristina
      Permalink to comment#

      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.

    • User Avatar
      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.

    • User Avatar
      Ian
      Permalink to comment#

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

    • User Avatar
      federico
      Permalink to comment#

      Very nice solution.

      I agree with above who say that absolute position is “relative” to the parent container if the parent container position is different from the default one (static).

      Anyway, very very nice, thanks.

  12. User Avatar
    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?

  13. User Avatar
    El garch Hicham
    Permalink to comment#

    Very nice thanks :D

  14. User Avatar
    Dominique
    Permalink to comment#

    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.

  15. User Avatar
    Dearthelusion

    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

  16. User Avatar
    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!

  17. User Avatar
    Mdbx
    Permalink to comment#

    @l3v1tcl30s

    $(function() {
      $("a").attr("target","_blank");
    });
    • User Avatar
      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

    • User Avatar
      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.

  18. User Avatar
    henk
    Permalink to comment#

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

  19. User Avatar
    Munawar
    Permalink to comment#

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

  20. User Avatar
    Josh
    Permalink to comment#

    Yeh roy! Thanks!

  21. User Avatar
    Ian
    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 ;)

  22. User Avatar
    Josias
    Permalink to comment#

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

  23. User Avatar
    ray van
    Permalink to comment#

    Nice tricks Thanks!

  24. User Avatar
    John Steelman
    Permalink to comment#

    Why not just do this:

    
      <div  onclick="location.href='webpage.html;" >
        [.... anything you want ...]
     </div>
    
    • User Avatar
      Shawn

      This is really simple and it works pretty well.

    • User Avatar
      Kalidasan
      Permalink to comment#

      Mr John, your idea is very simple & working fine for all browser types :)

  25. User Avatar
    Thomas Vanhoutte
    Permalink to comment#

    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

  26. User Avatar
    Max
    Permalink to comment#

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

  27. User Avatar
    Brandon
    Permalink to comment#

    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>
    
  28. User Avatar
    Tak

    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!

  29. User Avatar
    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;
    }

    • User Avatar
      lucas
      Permalink to comment#

      Or by inserting the following within your div tag:

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

  30. User Avatar
    Kevan H

    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 {}.

  31. User Avatar
    thom

    This is a javascript trick…not a CSS trick.

  32. User Avatar
    Romack Natividad
    Permalink to comment#

    thanks man, this works like magic

  33. User Avatar
    benelux
    Permalink to comment#

    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) ;    
    
  34. User Avatar
    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.

    • User Avatar
      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!

  35. User Avatar
    whitecreek
    Permalink to comment#

    Hi,

    Anyway to add target="_blank" to this:

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

    Simply adding:

    $(function() {
      $(".myBox a").attr("target","_blank");
    });</code></pre>
    

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

    Thanks in advance.

  36. User Avatar
    Rian
    Permalink to comment#

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

  37. User Avatar
    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.

  38. User Avatar
    Jonah
    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 .

  39. User Avatar
    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" rel="nofollow">link>/a>
    </div>
    
    $('.myBox').click(function(){
        $(this).find('a').trigger('click');
    });
    
  40. User Avatar
    Yosh
    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;
    });
    
  41. User Avatar
    Daniel
    Permalink to comment#

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

  42. User Avatar
    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

  43. User Avatar
    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" rel="nofollow">
      <div>My div contents</div>
    </a>
    

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

    • User Avatar
      Jeret
      Permalink to comment#

      Adam, this solution works like a charm. Thanks.

    • User Avatar
      Gianarlo
      Permalink to comment#

      Adam, Jaret,
      I think this is valid HTML 5 but is it valid HTML 4?

    • User Avatar
      Craig
      Permalink to comment#

      Adam,

      works like a charm. Beautifully simple, and effective. Thanks for passing along.

  44. User Avatar
    Guido Rus
    Permalink to comment#

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

    • User Avatar
      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…

  45. User Avatar
    David
    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”);
    }

  46. User Avatar
    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 */
    }
    
  47. User Avatar
    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?

  48. User Avatar
    SIFE
    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.

  49. User Avatar
    Simone

    Great! Fast and clean solution!

  50. User Avatar
    Nick

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

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

  51. User Avatar
    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;
    });
    
  52. User Avatar
    Ahmed

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

  53. User Avatar
    Denny
    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!

  54. User Avatar
    Alex
    Permalink to comment#

    I LOVE CSS-TRICKSDOTCOM!!!

  55. User Avatar
    Alex K.
    Permalink to comment#

    Very nice! Works like a charm!!

  56. User Avatar
    James Robertson
    Permalink to comment#

    But using target “_blank” – its not working

    Any ideas?

    Cheers

  57. User Avatar
    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

  58. User Avatar
    sanjeev
    Permalink to comment#

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

  59. User Avatar
    Muhammad Asif
    Permalink to comment#

    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

  60. User Avatar
    kgarske
    Permalink to comment#

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

  61. User Avatar
    hbirjand
    Permalink to comment#

    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/

  62. User Avatar
    Denny Smith
    Permalink to comment#

    You would need

    onClick="window.open('http://www.teamvalleylinks.com/')"
    
  63. User Avatar
    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 ....
    
  64. User Avatar
    Wojtek
    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.

  65. User Avatar
    Pooja
    Permalink to comment#

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

  66. User Avatar
    Akshay Joshi
    Permalink to comment#

    What if I have multiple Divs? Do you think that this code will work? Perhaps every div must have a unique id and unique js code. Can’t we just merge it?

  67. User Avatar
    Web Designer Pad
    Permalink to comment#

    Is there any HTML5 solution for this? JavaScript in huge websites just takes lots of time to load even if it’s placed in bottom.

  68. User Avatar
    Abhi
    Permalink to comment#

    <div>
    <a href="#" taregt="_blank">
    <div>
    </div>
    </a>
    </div>

  69. User Avatar
    Vinay
    Permalink to comment#

    Instead make a tag to display:block…

  70. User Avatar
    Seth

    Dude. THANKS!

  71. User Avatar
    Fred
    Permalink to comment#

    Great and simple.. Thanks saved the day

  72. User Avatar
    Emilio Garza
    Permalink to comment#

    I couldn’t agree more with Chris’ opening suggestion of just nesting your div within an Anchor tag. Way more friendly to update and the less JS for UI I can do the better IMHO. An anchor tag is meant to be a link, so much better for screen readers too.

    <a href="http://example.com">
      <div>
         anything
      </div>
    </a>
    

    I initially wrote something like this, but it just seems to ugly to me.

    <div class=".yourClass" data-url="http://www.example.com" target="_blank"></div>
    
    $(".yourClass").click(function() {
        var url = $(this).attr("data-url");
        var target = $(this).attr("target");    
        window.open(url,target);        
    }); 
    
    • User Avatar
      Tim
      Permalink to comment#

      Your second solution might be ugly, but it was perfect for what I needed to do in a site I’m working on right now. Thank you! =)

  73. User Avatar
    Britt

    The html5 technique unfortunately does not work with ModX. ModX deletes the <a> tag automatically when saving.

    Bummer.

  74. User Avatar
    Dave
    Permalink to comment#

    From my understanding, it’s not common practice to put divs within anchors. Is it now acceptable to do this, because I’ve heard both parties. One side is saying it’s not a good idea, the other side says it’s fine as long as there are no interactive items within the div that is being anchored.

    Some clarification on this matter would be helpful, thanks.

  75. User Avatar
    Damian
    Permalink to comment#

    Thanks for this! I used the jQuery method, works flawlessly :)

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag