Make a div or (other html object) into a link

January 23, 2010 9:32 pm Published by Leave your thoughts

If you need to transform a div, or any other HTML object, into a link here’s how…

Every now and again I need to transform a whole DIV into a hyperlink – say for example if I’m creating a button using a background image.

Using the background-image property in CSS you can place the graphic inside the DIV however because the image is referenced from CSS essentially the DIV is empty so there’s no html on which to hook your link.

There’s a couple of solutions, the quick and dirty method is to use the Javascript onclick event

The Javascript Onclick Event can be used on all of these html tags:

<a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var>

To create the link use the following code:

<div onclick=”location.href=’’;” style=”cursor:pointer;”></div>

However if you would like to open the link in a different window you can’t just use the ‘target=”_blank” attribute in your HTML because it’s not recognised by a DIV – it has to be included in the Javascript. To make the link open in a different window use:

<div onclick=”‘’,target=’_blank’,’width=800,height=600′)” style=”cursor:pointer;”></div>

Notice you can also specify the height and width of the new window.

Alternatively if you would like to use a more search engine friendly solution you can still use the <a> tag with href and title attributes.  Simply create the DIV with background image as before, now create a 1px by 1px transparent image, drop it into your DIV and resize accordingly – you can now wrap your transparent image complete with ALT text with an <a> tag and title attribute for maximum SEO.

<div><a href=”” title=”button description”><img src=”transparent-image.png” alt=”button description” width=”200″ height=”200″ /></a></div>

Categorised in:

This post was written by WillyNilly

Leave a Reply

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