There was a post on here a few years back about onclick show / hide divs.
This works until you add a div or a span inside of a tab*show link and then the content is hidden.
I have added a div sided of tab1show and when you click on it the content is hidden. Is there a way to get around this?
https://jsfiddle.net/amuv3f5L/
<pre>
<div id="tabShows">
<div id="tab1show">
<div>
test 1 default = show
</div>
</div>
<div id="tab2show">
test 2
</div>
<div id="tab3show">
test 3
</div>
<div id="tab4show">
test 4
</div>
<div id="tab5show">
test 5
</div>
</div>
</pre>
The issue is because you hide all child divs, not just the top level ones, and you never re-show the children. To fix this change the selector to:
$('#tabShows > div').hide();
Note the use of the >
selector. That being said, you can improve the logic by using common classes on all relevant elements, using CSS to hide content instead of JS, and using a
elements for the click events for better accessibility. Try this:
$('#clicks').on('click', 'a', function(e) {
e.preventDefault();
$('#tabShows > div').hide();
var target = $(this).attr('href');
$(target).show();
});
#tabShows > div { display: none; }
#tabShows #tab1 { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="clicks">
<a href="#tab1">Test 1</a>
<a href="#tab2">Test 2</a>
<a href="#tab3">Test 3</a>
<a href="#tab4">Test 4</a>
<a href="#tab5">Test 5</a>
</div>
<br /><br />
<div id="tabShows">
<div id="tab1">
<div>test 1 default = show</div>
</div>
<div id="tab2">test 2</div>
<div id="tab3">test 3</div>
<div id="tab4">test 4</div>
<div id="tab5">test 5</div>
</div>