Ron Brouwers Ron Brouwers - 1 year ago 134
jQuery Question

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:

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

$('#tab1').click(function () {


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

Answer Source

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');
$('.tab').click(function() {
  var $target = $('#' + + 'show').show();
<script src=""></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 id="tab2show" class="tab-content">
  test 2

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

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

<div id="tab5show" class="tab-content">
  test 5

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download