Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery onclick show / hide multiple divs

I am trying to learn some jQuery and appearantly I haven't learned anything from my last questions and the answers I've got, since I cannot figure out how to do the following:

https://jsfiddle.net/9eofcw7w/

Yes, it's working, but code like this is just sloppy and is not professional:

$('#tab1').click(function () {
$('#tab2show').hide();
$('#tab3show').hide();
$('#tab4show').hide();
$('#tab5show').hide();

$('#tab1show').show();
});

How would I go about making the above code with just a few lines of jQuery instead of the stuff I have right now?

like image 895
Hardist Avatar asked Jul 18 '15 09:07

Hardist


1 Answers

The problem with your code is you are repeating the same block of code for each element, instead you can use some common attributes to reduce the separate handlers like

First we add a common class to all the tab elements like tab, then another class tab-content is added to all the content elements, this will help us to select those elements easily.

Then the logic we are looking for is, we need to show only that content whose id matches with the clicked tab(the id of the content is <clicked tab id> + 'show').

Now we can have a single click handler which will target all the tab elements, in which we concatenate its id with 'show' to find the content to be shown and displays it via .show() then we hides all other tab-content elements.

Also note that we can cache the jQuery object for tab-content for later use.

var $contents = $('.tab-content');
$contents.slice(1).hide();
$('.tab').click(function() {
  var $target = $('#' + this.id + 'show').show();
  $contents.not($target).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="tab1" class="tab">Test 1</div>
<div id="tab2" class="tab">Test 2</div>
<div id="tab3" class="tab">Test 3</div>
<div id="tab4" class="tab">Test 4</div>
<div id="tab5" class="tab">Test 5</div>

<br />
<br />

<div id="tab1show" class="tab-content">
  test 1 default = show
</div>

<div id="tab2show" class="tab-content">
  test 2
</div>

<div id="tab3show" class="tab-content">
  test 3
</div>

<div id="tab4show" class="tab-content">
  test 4
</div>

<div id="tab5show" class="tab-content">
  test 5
</div>
like image 130
Arun P Johny Avatar answered Sep 22 '22 23:09

Arun P Johny