Clickable box with jQuery

Posted by Matt on Sun, Sep 07 2008

I use this trick a lot. Often I'll have an box with an H tag and an area below it with some detail text. I want to make the whole box clickable based on the link in the H tag. Here's an example of what I'm talking about:

Section Title

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras non est vel neque ornare porta. Donec convallis. Nam odio felis, euismod quis, molestie sed, auctor quis, purus. Donec eu dolor.

The HTML for this box is simple:

<div class="section">
    <h3><a href="/link/to">Section Title</a></h3>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras non est vel neque ornare porta. Donec convallis. Nam odio felis, euismod quis, molestie sed, auctor quis, purus. Donec eu dolor.</p>
</div>

I'll leave the CSS up to you, but be sure to include at least this section, which forces the link to fill the entire H area:

.section h3 a {
  display: block;
}

Adding this simple jQuery makes the whole area clickable, linking to the same page as set in the H tag.

$(".section").click(function() {
  window.location = $(this).find("h3:first a:first").attr("href");
});

If you want to get fancy you can also add a hover effect:

    $(".section").hover(
      function() {
        $(this).addClass("hover");
        $(this).append('<div class="learn-more">Learn More</div>');
      },
      function() {
        $(this).removeClass("hover");
        $(".learn-more").remove();
      }
    );

The original box above is an example of all this put together.

Posted in Code

25 Comments

Marc Grabanski said on Sep 08, 2008
Small fix: your markup has, but your selectors and CSS are using . Also you should probably post the CSS for ".section" and ".learn-more". Some might not be familiar with CSS positioning.

Glad to see you using jQuery!
Matt said on Sep 08, 2008
Hey Marc,
Thanks for pointing that out. I usually use h2, but made it h3 to take advantage of an existing style for this blog. I missed changing it everywhere.

Here's the CSS for all the elements:



Baris Wanschers said on Mar 27, 2009
Really useful! Works like a charm. This why I love jQuery: so little code and so usable. Thanks for posting.
alon said on Mar 09, 2010
very nice technice, thank you !