Yin Yin - 4 months ago 23
HTML Question

Javascript .hide() and .show() not working

I have following html:

<div class="menu_tab row">
<div class="active" rel="#tab1">Tab 1</div>
<div rel="#tab2">Tab 2</div>
<div rel="#tab3">Tab 3</div>
<div rel="#tab4">Tab 4</div>
</div>
...
<div id="tab1" class="tab_content">...</div>
<div id="tab2" class="tab_content">...</div>
<div id="tab3" class="tab_content">...</div>
<div id="tab4" class="tab_content">...</div>


And following javascript inside seperate js file:

$(document).ready(function () {
$(".tab_content").hide();
$(".tab_content:first").show();
});

$(document).on('click', ".menu_tab div", function() {
$(".menu_tab div").removeClass("active");
$(this).addClass("active");
$(".tab_content").hide();
var activeTab = $(this).attr("rel");
$(activeTab).show();
});


I can click on the menu tab and the tab is changed. But the problem is when the app is first loaded, it displays all four tabs but when I click, it works correctly. So what I think is, this part of code:

$(document).ready(function () {
$(".tab_content").hide();
$(".tab_content:first").show();
});


is not working. Can someone tell me why? Thanks in advance!

Answer

Try the following:

$(".tab_content").hide();
var activeTab = $('.active').attr("rel");
$(activeTab).show();

or use css:

.tab_content {display:none;}
.tab_content:first-child {display:block;}
Comments