Deano
Deano

Reputation: 12190

jquery tab like effect - show hide div on click

I'm learning jquery, and I'm trying to create a tab like effect "upon click, only a single div should show at a time", I have wrote the following, but I don't feel its the correct way of doing things even tho the my code works. Any idea how I can improve this? maybe make it a function?

here is a working demo

$(document).ready(function(){
  $("#tabone").click(function(){
        $('#box-one').css("display", "block");
        $('#box-two').css("display", "none");
        $('#box-three').css("display", "none");
  });
});

$(document).ready(function(){
  $("#tabtwo").click(function(){
        $('#box-one').css("display", "none");
        $('#box-two').css("display", "block");
        $('#box-three').css("display", "none");
  });
});

$(document).ready(function(){
  $("#tabthree").click(function(){
        $('#box-one').css("display", "none");
        $('#box-two').css("display", "none");
        $('#box-three').css("display", "block");
  });
});

Thank you

Upvotes: 3

Views: 12249

Answers (3)

Gary Storey
Gary Storey

Reputation: 1814

Only one click event and uses the newer on method.

$("#ul-menu-list").on('click','li', function(e) {
  $('.box').hide().eq($(this).index()).show();
});

Upvotes: 2

Balachandran
Balachandran

Reputation: 9637

Use common class like .box based on that You can hide and show the div using selected index()

HTML

<ul id="ul-menu-list">
    <li id="tabone">How it Works</li>
    <li id="tabtwo">Features</li>
    <li id="tabthree">FAQ</li>
</ul>
<di id="box-one" class="box">Tab one</di>
<di id="box-two" class="box">Tab two</di>
<di id="box-three" class="box">Tab three</di>

JS

$(document).ready(function(){
    $("#ul-menu-list li").click(function () {
        $('.box').hide().eq($(this).index()).show();  // hide all divs and show the current div
    });
});

DEMO

Upvotes: 7

Mritunjay
Mritunjay

Reputation: 25882

I'm not sure what di element is but this will work anyway for you, if structure is going to be same.

$(document).ready(function(){
  $("ul li").click(function(){
      $('di[id^="box-"]').css("display", "none");
      $('di[id^="box-"]').eq($(this).index()).css("display", "block");
  });
});

DEMO

Upvotes: 1

Related Questions