Creating a Linked Box (div)

This has been updated using jquery.

It’s easy to make a piece of text into a link, but what do you do when you want to make an entire area clickable?

Beginning web developers might try to wrap the entire div in an anchor tag. While this might work for some browsers, it isn’t valid HTML because anchor tags (<a href=””>) can not contain block level elements (like div).

We’ll start with a basic div with some text.

  <div id="box">
    <p>Linked Div</p>
    <p>By Llynix</p>
  </div>

Our first step is to make everything inside this box linkable. This is ensure proper fallback when dealing with Javascript disabled browsers.

  <div id="box">
    <p><a href="#">Linked Div</a></p>
    <p><a href="#">By Llynix</a></p>
  </div>

Now we’ll add our Javascript which does the job for us.

  <div id="box" onclick="javascript:window.location = '#';">
    <p><a href="#">Linked Div</a></p>
    <p><a href="#">By Llynix</a></p>
  </div>

Finally we can add some CSS to make it behave more like a link.

  <style type="text/css">
    #box {height:100px;width:100px;border:1px solid black;} /* Just some style to our div */
    #box {cursor:pointer;}
    #box:hover {background-color:yellow;}
  </style>

And there you have it. View example

Leave a Reply

Your email address will not be published. Required fields are marked *