I use following code to display tabs. However I am failing to understand why js throws an error. Function opentab accepts 2 arguments (id of contentab and id of button). It seems there is some problem in last row of js because it fails to add class "active" to clicked button. Can anybody help? Thank you.
function opentab(tabname, evt) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabname).style.display = "block";
evt.currentTarget.className += " active";
}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
font-size: 17px;
float: left;
margin-right: 5px;
margin-bottom: 0;
padding: 14px 16px;
cursor: pointer;
-webkit-transition: .3s;
-o-transition: .3s;
transition: .3s;
border: none;
border-radius: 0;
outline: none;
background-color: inherit;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
-webkit-transition: opacity .3s;
-o-transition: opacity .3s;
transition: opacity .3s;
-webkit-animation: fadeEffect 1s;
animation: fadeEffect 1s;
opacity: 1;
border: 1px solid #ccc;
border-top: none;
}
/* Fade in tabs */
@-webkit-keyframes fadeEffect {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeEffect {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<div class="tab">
<button class="tablinks active" id="btn1" onclick="opentab('tab1','btn1')">Tab 1</button><button id="btn2" class="tablinks" onclick="opentab('tab2', 'btn2')">Tab 2</button><button id="btn3" class="tablinks _danger" onclick="opentab('tab3, btn3')">Tab 3</button>
</div>
<div class="tabcontent" id="tab1">
<h3>
A simple Tab
</h3>
<p>
London is the capital city of England.
</p>
</div>
<div class="tabcontent _primary" id="tab2">
<h3>
Another Tab
</h3>
<p>
You can add colors too.
</p>
<button class="_nightblue">Wow</button>
</div>
<div class="tabcontent" id="tab3">
<div class="-close _floatRight _f-danger">
×
</div>
<h3>
Tab with close button
</h3>
<p>
Do you see a × above ?
</p>
</div>
onclick="opentab('tab1', 'btn1')"
...onclick="opentab('tab1', event)"
. Your code is expecting an event as the second parameter, but you're passing in a string.