joepie91's Ramblings

home RSS

Simple snippet of jQuery code to create a clickable anything without breaking middle-click

06 Sep 2012

If you've ever made something like a directory listing or supposedly clickable items in a table, you've no doubt experienced the need to make entire table rows clickable. The following snippet of code will not only take care of that, but it will also turn anything - literally anything! - into something clickable. Here comes the kicker: *it makes things clickable as if they are a normal hyperlink, without being in the way of habits like middle-clicking. *It uses a data attribute and simple classes to keep your markup clean.

When you click on one of these elements with your middle mouse button, it will open the target URL in a new tab or page, just like a hyperlink would. This means that the common issue where certain elements replace the current page when middle-clicking (whereas the user would expect them to open in a new tab), no longer occurs. 

It also allows you to specify external links - these will be opened in a new tab or window (depending on user settings) regardless of whether they are left-clicked or middle-clicked. Here comes the code:

$(document).ready(function() 
{
    $('.clickable').click(function(event)
    {
        if($(this).data('url'))
        {
            url = $(this).data('url');

            if(event.which == 1)
            {
                if($(this).hasClass('external'))
                {
                    window.open(url);
                }
                else
                {
                    window.location = url;
                }
            }
            else if(event.which == 2)
            {
                window.open(url);
            }
        }
    });     
});

Here's how you use it for an internal link:

<tr class="clickable" data-url="http://www.targetsite.com/targetpage.html">  
    <td>Some content goes here.</td>  
    <td>Another cell of content goes here.</td>  
</tr>

Here's how you use it for an external link (note the extra class!):

<tr class="clickable external" data-url="http://www.externalsite.com/targetpage.html">  
    <td>Some (external) content goes here.</td>  
    <td>When you click this row, it will send you to an external page in a new tab.</td>  
</tr>

*Obligatory warning: do not use this for normal hyperlinks! *This solution requires Javascript, and you should never rely on something that uses Javascript unless there is no other option. If you can use a normal hyperlink without breaking your document validity, then use that option!

What if you want your table row to also be clickable to users without Javascript? While not a perfect solution, an acceptable fallback is putting the text in the most important table cell, in an <a> element. This way there is at least something that users without Javascript can click. This approach will not conflict with the above snippet of code.