Jquery tab as effect - show hide div on click

I am learning jquery and I am trying to create a tab as a "on click, only one div should show at a time" effect, I wrote the following, but I don't think its the correct way to do things even in my code works. Any idea how I can improve this? maybe this is a function?

demo works here

$(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

+3


source to share


3 answers


Use a generic class, for example .box

based on what you can hide and show div with highlighted 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

+7


source


Only one click event and uses a new method on

.



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

      

+2


source


I'm not sure what the element is di

, but it will work anyway for you if the structure is the same.

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

      

DEMO

+1


source







All Articles