Search code examples
jquerytabsjquery-tabs

jquery tabs - im having trouble making my <li> clickable


This is my tabbed interface, I have a jsfiddle here.

<div class="tabs">
  <!-- tabs -->
  <ul class="tabNavigation">
    <li><a href="#corporations">Corporations</a></li>
    <li><a href="#non-profit">non-profit</a></li>
    <li><a href="#growing-businesses">growing-businesses</a></li>
    <li><a href="#arrange">Arrange a meetup</a></li>
  </ul>

  <!-- tab containers -->
  <div id="corporations">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
  <div id="non-profit">
    <p>Sed do eiusmod tempor incididunt.</p>
  </div>
  <div id="growing-businesses">
    <p>Ut enim ad minim veniam</p>
  </div>
  <div id="arrange">
    <p>Sed do ad minim ipsum dolor sit</p>
  </div>
</div>

This is my jquery which is simple enough.

$(function () {
    var tabContainers = $('div.tabs > div');

    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();

        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');

        return false;
    }).filter(':first').click();
});

My problem is I know how to easily manipulate an <a> in order to change the contents on hover or click, which I have already done in the jsfiddle. But I want to hover or click the <li> and change the information in the container to show.


Solution

  • All you need to do is select the <li> elements and bind a click event handler, just the same as for a link:

    $(function () {
        var tabContainers = $('div.tabs > div');
    
        //here I am targeting the `<li>` elements instead of the `<a>` elements
        $('div.tabs ul.tabNavigation li').click(function () {
    
            //to get the "hash" you need to select the child `<a>` element of this `<li>` element
            var the_hash = $(this).children().attr('href');
            tabContainers.hide().filter(the_hash).show();
    
            //and here the `selected` class is being added and removed from the `<li>` elements rather than the `<a>` elements
            $('div.tabs ul.tabNavigation li').removeClass('selected');
            $(this).addClass('selected');
    
            return false;
        }).filter(':first').click();
    });
    

    Here is an updated version of your jsfiddle: http://jsfiddle.net/3EyCT/5/