somtodaynt/popup/js/index.js

89 lines
2.5 KiB
JavaScript

console.log("SOMtodayn't popup loaded.");
var request;
var response;
// Get slogans from background script
request = browser.runtime.sendMessage({
type: "get"
});
request.then(function(message) {
var darkmode = message.response[0];
var sloganArray = message.response[1];
// Add a slogan to the array
function addSlogan(value) {
sloganArray.push(value);
updateSlogans(sloganArray);
}
// Remove a slogan from the array
function removeSlogan(id) {
var array = [];
if (sloganArray.length > 1) {
for (let index = 0; index < sloganArray.length; index++) {
const element = sloganArray[index];
if (index != id) {
array.push(element);
}
}
updateSlogans(array);
} else {
window.alert("U kunt de laatste slogan niet verwijderen.");
}
}
// Send updated array to background script
function updateSlogans(array) {
request = browser.runtime.sendMessage({
type: "setSlogans",
value: array
});
request.then(function() {
location.reload();
}, handleError);
}
// Add event listener to checkbox
var checkbox = document.getElementById('tonight');
if (darkmode) {
checkbox.checked = true;
}
checkbox.addEventListener('click', function(event) {
request = browser.runtime.sendMessage({
type: "setTonight",
value: checkbox.checked
});
});
// Add existing slogans to list items in the popup
var sloganList = '';
for (let index = 0; index < sloganArray.length; index++) {
const element = sloganArray[index];
sloganList = sloganList + `<ul>${element}</ul>`;
}
document.getElementById('sloganList').innerHTML = sloganList;
// Get value for new slogan
document.getElementById('sloganForm').addEventListener('submit', function(event) {
event.preventDefault();
addSlogan(event.target.children[0].value);
event.target.children[0].value = '';
});
// Add event listener to every list item for deleting slogans
var listElements = document.querySelectorAll("div#sloganList > ul");
for (let index = 0; index < listElements.length; index++) {
const element = listElements[index];
element.addEventListener("click", function() {
removeSlogan(index);
});
}
}, handleError);
function handleError(error) {
console.error(`SOMtodayn't Error: ${error}`);
}