Reputation: 652
Currently, I am using the guide at the following link to determine how to build tabs (http://www.w3schools.com/howto/howto_js_tabs.asp).
function openTab(evt, tabName) {
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";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
I want to change the tab that is displayed upon pressing a button. Therefore, in the eventListener code in javascript:
document.getElementById("btn_click").addEventListener("click", function() {
openTab("click", "tab2");
}
This gives me that "click" as evt is undefined. Would appreciate any help in how to define the parameter evt to change tabs upon pressing the button (a javascript soln would be preferable).
Upvotes: 1
Views: 912
Reputation: 18925
You need to pass the actual click event like so:
document.getElementById("btn_click").addEventListener("click", function(e){
openTab(e, "tab2");
})
Also as a general rule: try to avoid w3schools are the plague. Quality is overall very low. Better bet is to just search stackoverflow for solutions to specific questions, and use mozilla for reference to all things DOM-related.
Upvotes: 2
Reputation: 6433
You as it says on the w3schools website, you just have to run this code when the button is pressed.
function openCity(evt, cityName) {
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(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
Here is both the HTML and JS: http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_tabs
Hope this helps!
Upvotes: 2