Skip to content

Instantly share code, notes, and snippets.

@mikedoubintchik
Created May 9, 2017 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedoubintchik/15187d4e31e0296588f3d2e529bb6915 to your computer and use it in GitHub Desktop.
Save mikedoubintchik/15187d4e31e0296588f3d2e529bb6915 to your computer and use it in GitHub Desktop.
// This is the usual approach to creating functions in JS
var waitingList = [];
var buttons = document.querySelectorAll("button");
var input = document.querySelector("input");
var waitingListContainer = document.getElementById("waiting-list");
function addPeople(people) {
if (Array.isArray(people)) {
people.forEach(function(person, index) {
waitingList.push(person);
});
} else {
waitingList.push(people);
}
}
function removePeople(people) {
if (Array.isArray(people)) {
people.forEach(function(person, index) {
index = waitingList.indexOf(person);
waitingList.splice(index, 1);
});
} else {
index = waitingList.indexOf(people);
waitingList.splice(index, 1);
}
}
function updateWaitingList() {
var waitingListHtml = "";
waitingList.forEach(function(person, index) {
waitingListHtml += "<li>" + person + "</li>";
});
waitingListContainer.innerHTML = waitingListHtml;
}
function bindEvents() {
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function(e){
var people = input.value;
if (people.includes(",")) {
people = people.split(",");
}
if (people !== "") {
if (e.target.className === "add") {
addPeople(people);
updateWaitingList();
}
if (e.target.className === "remove") {
removePeople(people);
updateWaitingList();
}
} else {
alert("Please enter a name");
}
});
}
}
bindEvents();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment