Today my partners and I were where working on a snazzy little javascript list maker called List.io.
Basically, you add a task to the form click on the New Task button and it will create to do items in a list. Each item in the list will have a 'completed' button and a 'delete' button.
Everything worked great when we where testing one item. But when we made an actual list of more than three items and began to click them as 'completed', we got an error:
The error says "Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist." It occurs on line 19: actionDiv.removeChild(completeButton);
var listItems =[];
function makeElem(list){
li = document.createElement("li"); //creating li
itemDiv = document.createElement("div"); //creating div
itemDiv.setAttribute("class", "items"); //creating the class name
itemDiv.innerHTML = list[list.length -1]; //put inside div the last thing in array
var actionDiv = document.createElement("div");
actionDiv.setAttribute("class", "actions");
completeButton = document.createElement("button"); //create button
completeButton.setAttribute("id", "complete"); //give button the complete attribute
completeButton.innerHTML = "complete"; //label the button 'complete'
completeButton.addEventListener("click", function(){
console.log(actionDiv);
console.log(completeButton);
actionDiv.removeChild(completeButton);
completeTasks.appendChild(li);
}); etc...
Can you guess what's wrong with this picture?
Exactly, the global namespace is crazy polluted, yo!
And because it was polluted, our "actionDiv" which among other things, removed the 'completed' button, stopped working.
Lets add some vars to clean it up like so:
var listItems =[];
function makeElem(list){
--> var li = document.createElement("li"); //creating li
--> var itemDiv = document.createElement("div"); //creating div
itemDiv.setAttribute("class", "items"); //creating the class name
itemDiv.innerHTML = list[list.length -1]; //put inside div the last thing in array
--> var actionDiv = document.createElement("div");
actionDiv.setAttribute("class", "actions");
--> var completeButton = document.createElement("button"); //create button
completeButton.setAttribute("id", "complete"); //give button the complete attribute
completeButton.innerHTML = "complete"; //label the button 'complete'
completeButton.addEventListener("click", function(){
console.log(actionDiv);
console.log(completeButton);
actionDiv.removeChild(completeButton);
completeTasks.appendChild(li);
}); etc...
By NOT declaring the variables with "var" INSIDE your function, you are in effect creating a variable outside of the function which makes it a global variable which can be overwritten, disappear, muck things up...in essence, POLLUTE the global namespace, dude. So if you ever get a funky error, like we did, check to see if you need to give hoot and mind your vars.