Clickable DIVs – jQuery plugin

by
on May 10, 2011
(2 minute read)


Clickable DIVs jQuery plugin will convert anything (<div>, <li>, <p>, etc.) into a clickable object. It is a great way to enhance the usability of your website by increasing the clickable space to your users while avoiding extra HTML markup or a somehow tedious re-coding of your website.

  • Works with JavaScript disabled too (graceful degradation)
  • Works in all modern, mobile and old browsers: Firefox, Chrome, Opera, Safari, Internet Explorer (including IE6), touch screens (iPhone, iPad, Android), etc.
  • Detects if link needs to be opened in a new page or the same one
  • 1 line of code, easy to install (paste the code and add click class to the div)
  • Works with div, li, p, h1 or any other HTML element

This small plugin is being used in this website already. This is how my front page looks like:

The red area symbolizes the clickable area where the link would work for users visiting the website. The black square shows you the existing markup of each listed item.

By adding a simple click class to the list element, it inherits the click bind of the <a> in it and everything becomes a link. The plugin will also detect if the link is set to open in a new window. Look at the clickable area after enabling the plugin:

You can see a working demo at the bottom of this page.

Usage

You could add this plugin as an external file but since it is so tiny, the best way of doing it is to embed it into an existing .js file.
1. Add this code inside the DOM ready function of your jQuery:

/* Clickable divs - Copyright Xavi Esteve 2011 Dual licensed under the MIT or GPL Version 2 licenses. https://xaviesteve.com//clickable-divs-jquery-plugin */
$('.click').css("cursor","pointer").click(function(){var link=$(this).find('a:first');var linkhref=link.attr('href');if(link.attr('target')){var newWindow=window.open(linkhref,link.attr('target'));newWindow.focus()}else{window.location=linkhref}return false});

I’ve got invites for a free bank transfer!

2. Add the CSS class link to any element you want to inherit the click (a <li> for example).

Source code

Feel free to modify and improve the script by going to ClickableDivs at jsFiddle.

Did you enjoy this article?

Thank with a coffee ☕

Or help me out by clicking one of these buttons:

    
    

37 comments

  • Tim says:

    This is amazingly good. I intend to use this for pretty much all my Phonegap projects!

  • Xavi Author says:

    Thanks Tim, that’s the purpose of this project, it is a great lightweight start without requiring any heavy library or restricting license. If you find any issues let me know and I’ll help you fix them. Please let me know if you launch any apps with it, I’ll be glad to feature them in this post.

  • inyman says:

    Great work !

  • Eric says:

    Nice job… We will use this on one of our upcoming projects! This really helps.

  • Josiah Sprague says:

    That’s pretty cool. It even degrades acceptably in IE8 (the farthest back I personally care about). One enhancement you might try is setting user-select to none on some of the interface elements that shouldn’t be selectable. Really great work! Thanks for sharing this!

  • 185 says:

    Simply love it!

    You can add -webkit-touch-callout: none; to disable the callout shown when you touch and hold a touch target.

    Also, sometimes when clicking a link in web apps they may open in Safari, you can fix that by using a script like gist.github.com/1042026

  • kirubai says:

    Great Job! :-)

  • Purged Reality says:

    Awesome! Love this.

  • Lee says:

    This infinately contributes to the Public Domain License. You sir, are a scholar and a gentleman. Please continue to update and improve this. Also, look into some donation services and get some buttons put up.

    How do I completely remove the sidebar? Everything I tried removed the sidebar but the content does not go fullscreen… it still acts as if the sidebar is there, just not being displayed.

  • Xavi Author says:

    Thanks everyone for the comments, I’m glad you like it.

    Lee,
    To hide the sidebar you will need to resize some main content elements. See the CSS at the end of the ‘style’ tag that starts like this:
    @media only screen and (max-width: 768px) {

  • Clem says:

    Great job, it’s really usefull and really well thinked ! GG

  • shatle says:

    how can i remove the ‘delete account’ ? i can not find the html tag. i am a student.

  • Joshua Sailsbery says:

    Freak’n awesome

  • bored-student says:

    Wow, just what I’ve been looking for all day. Just ran this on the android simulator and it has amazing performance compared to other templates I’ve been looking at today.

    I’m going to split it up and create a base template for applications created using PhoneGap. A good template that can be used on iOS, Android and other mobile touch devices is certainly needed. I’ll post a link to the finished version on here once done.

    Note: I’m not a pro at HTML/CSS so this may take a week or two.

  • Xavi Author says:

    That’s great news bored-student :)
    It’s so fast because it doesn’t use any JavaScript at all and the code has been hugely optimised to be both small and fast to render.
    If you have any doubts with HTML/CSS let me know, I’ll be glad to collaborate in the creation a PhoneGap template.

  • bored-student says:

    So I’ve done abit of work on my template for PhoneGap that is based on this template. The template is in it’s early stages of development but version 1.0 can be downloaded from:
    http://www.bored-student.com/phonegap-ui-template/

    A Google Code project has been set up under the Apache 2.0 License to develop this template further. All details can be found on the page link above.

    I hope people find it useful and it would be great for other developers to get involved with the project who have some expertise and time.

  • Kryton says:

    Very nice template as this kick started my project with a few mods. On the table there is a border around it in your sample as well as mine and I’ve tried to get rid of it with no luck. Any ideas?

  • Xavi Author says:

    Hi Kryton,
    I spent some time trying to get the corners rounded and there is no way yet, searching around the Internet it seems it is a bug from browsers (or it hasn’t been implemented yet). Problem is that the borders are not set in the table but in its tbody.
    The alternative is to just remove the border in the CSS here:
    #main table tbody {border: 1px solid #B4B7BB;}
    Glad to hear you are using the template, I’d love to see what you come up with.

  • Luis García says:

    Gracias por este impresionante trabajo sin imágenes.
    Viene lo vectorial y para quedarse. El diseño y la programación se funden y tu lo has logrado con este fantástico template.
    Enhorabuena y muchísimas gracias.
    Cuando termine mi proyecto (algún día) te enviaré el resultado.

  • Charlie K says:

    Thanks for the great template!
    This may be a solution for the table corners problem. Move the white background color from tbody to the individual table cells (tbody tr td), then replace the existing “Dirty fix…” with the following:

    #main table {
    border-collapse: separate;
    }
    #main table tbody tr td{
    border-top:1px solid #B4B7BB;
    }
    #main table tbody tr:last-child td{
    border-bottom:1px solid #B4B7BB;
    }
    #main table tbody tr td:last-child{
    border-right:1px solid #B4B7BB;
    }
    #main table tbody tr td:first-child{
    border-left:1px solid #B4B7BB;
    }
    #main table tbody tr:first-child td:first-child {
    border-top-left-radius:10px;
    }
    #main table tbody tr:first-child td:last-child {
    border-top-right-radius:10px;
    }
    #main table tbody tr:last-child td:first-child {
    border-bottom-left-radius:10px;
    }
    #main table tbody tr:last-child td:last-child {
    border-bottom-right-radius:10px;
    }

    Tested in latest Firefox, Chrome, Safari(Mac). Hope it helps.

  • rox says:

    now this is beautiful..great work .. thanks for share !!

  • idevi says:

    Great work! I am glad I found this template. One little problem. How can I get the side bar to scroll on an Android Tablet 3.2.1 – I thought I might change this:]

    /* All portable */
    @media only screen and (max-device-width: 1024px) {
    #sidebar {overflow:scroll;} /* Sidebar is only scrollable in portable devices, you can change that */
    }
    /* iPhone */
    @media only screen and (max-width: 768px) {
    #sidebar {display:scroll;}<————————————**
    #main {padding-left:20px;}
    #main .header {padding-left:0;}
    #main .header .left {left:10px;}
    No luck. Any suggestions? Thank you again!

  • Lee Wen says:

    Excelent work. Congratulations. I was looking hours for this and nothing is better than yours.
    Thank you

  • Ted Wilson says:

    I already have a database created and managed with MySQL Workbench, where do it enter the details? How can I use the fix it in Workbench?

    Thanks

  • Jack says:

    This is great!

    Do you have a version of this with an additional left column for a Country/State/Detail style interface?

  • LC says:

    Very nice template, I’m currently transitioning a web app to use this new template. I will send the author the link to the application by roughly the end of the week.
    Only one issue I encountered is by adding a form tag around p input styled elements get crunched (looks to be margin). Seems wrapping with form modifies the context they are in.

  • Tomas says:

    Actualmente solo resta esperar que la empresa Apple realice
    lo esperado y disponga su esperado producto para cumplir las
    necesidades de lo que se quiere con dicho móvil y una vez lo tengan en su poder disfrútenlo de verdad porque
    necesitarán tiempo para conocer todas sus posibilidades y aplicaciones que
    harán su rutina mucho más sencilla y divertida.

  • Fred says:

    Great stuff Xavi,

    Definitely going to use this for an app. How do I go about inserting icons into the sidebar links where there’s a grey square? Couldn’t work it out…

    Thanks!

  • Lester Hurtado says:

    Nice work. How do you intend to replicate the smooth transition from one web page to the next once a button is clicked? Thanks – Lester

  • W says:

    I’m thinking about first using your template for a desktop web app, which will eventually move to the ipad. For now, I’m having trouble figuring out how to get the sidebar to scroll along with the main content… if the web browser window is not tall, I cannot see the entire left navigation area, and scrolling only will move the right panel.

  • James says:

    Xavi,
    I’m using your template and it’s really great. It works very well but I’m having the problem with the fixed header moving as described in this note from the top of the template.php page:

    Notes:
    – Header position bug when scrolling: When you scroll down, the header may move to the middle of the screen. Fix it by removing the # from the URL.

    I do not have a “#” in my URL. I’m not certain of what you’re talking about removing. Can you please clarify or suggest what else might be causing the header to move?

    Thank you,
    James

  • Jeff says:

    Great Template! Will be using it for a new App now being developed. One issue I have been struggling with is how to add another button alongside the .left in the .main.header?
    Any help appreciated.
    cheers

  • Tim says:

    My layout goes left somehow on my ipad. Is there any issue with that?

  • edmundo says:

    thanks a lot i could do 2 day version of my web page with your template pda.lcda.org thanks a lot i’m very grateful xavi

  • Corey Avis says:

    Great template! One addition I would like to see… You have a red button, for Delete and Remove buttons, but a green style for other more positive buttons would be nice.

  • Corey Avis says:

    An error I’ve come across… You didn’t account for form elements actually being put in a form. The margin is lost around paragraph elements leaving no space between elements inside a form. To correct this, find this line:
    #main .content>p
    and change it to:
    #main .content>p, #main .content form>p

  • dbair says:

    Great template!
    Can you add a menu structure that consists of sub menu items?

Follow me for cool new products and interesting findings on graphic design, web development, marketing, startups, life and humor.


/*Twitter*/ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); /*Facebook*/ (function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=28624667607";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk')); /*Google+*/ window.___gcfg = {lang: 'en-GB'};(function() {var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;po.src = 'https://apis.google.com/js/plusone.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);})();
Airbnb 25€ discount