I've been trying to learn javascript by refactoring some Jquery examples in a book into javascript. In the following code I add a click listener to a tab and make it change to active when the user clicks on the tab.
var tabs = document.querySelectorAll(".tabs a span");
var content = document.querySelectorAll("main .content li");
for (var tabNumber = 0; tabNumber <= 2; tabNumber++) {
tabs[tabNumber].addEventListener("click", function (event) {
for (var i = 0; i < tabs.length; i++) {
tabs[i].classList.remove("active");
}
tabs[tabNumber].classList.add("active");
for (var i = 0; i < content.length; i++) {
content[i].innerHTML = "";
}
event.preventDefault();
});
}
This returns an undefined error
when I run it. However, I tried replacing tabs[tabNumber].classList.add("active")
with this.classList.add("active")
and it worked.
Why doesn't the previous code work? As far as I can see they are referring to the same thing, and tabs[tabNumber]
should work since at that point in the code it is tabs[0]
.
JavaScript is so hard to learn because it's an asynchronous programming language. It's also single-threaded, which means it uses its asynchronous nature in a radically different way than most other programming languages.
On the web browser menu click on the "Edit" and select "Preferences". In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox. Click on the "Reload the current page" button of the web browser to refresh the page.
Namely, with JavaScript, most of our errors fit into two categories: syntax errors and runtime errors. A syntax error is a problem with the grammar in our code. Syntax errors mostly come in the form of misspelled keywords, missing or open brackets, or missing parentheses or punctuation.
If use this
, I think it's better and a more polished solution. If you still want to use tabNumber
, it's probably evaluating to 3
in every click callback, because it's the number after the last iteration, and you don't have a tabs[3]
position.
So, you just have to make a closure of the tabNumber
variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With