Toggling not working properly - Javascript - javascript

I have this code which sould toggle between elements, if user opens the element all other elements should close and that works, but if I click on the same element multiple times nothing happens and I cant figure out why. I need some help.
Here is my code:
const heads = [...document.querySelectorAll(".head")];
const dropdowns = [...document.querySelectorAll(".head-dropdown")];
const activate_filter = document.getElementById("filter-btn");
let isActive = false;
let isFilterActive = false;
let queue = [];
if (!isFilterActive) {
dropdowns.forEach((val, i) => {
val
.querySelector(".dropdown-search")
.setAttribute(
"name",
`${heads[i].querySelector("p").textContent}-search`
);
});
}
activate_filter.addEventListener("click", e => {
dropdowns.forEach((val, i) => {
val.classList.remove("activated");
val.dataset.isActivated = false;
});
if (!isFilterActive) {
heads.forEach((val, i) => {
const p = val.children[0];
p.innerHTML += `<i class='eos-icons'>arrow_drop_down</i>`;
val.addEventListener("click", handleEventAll);
val.style.cursor = "pointer";
});
isFilterActive = true;
} else {
heads.forEach(val => {
const p = val.children[0];
const i = p.querySelector("i");
if (i) {
i.remove();
}
val.removeEventListener("click", handleEventAll);
val.style.cursor = "default";
});
isFilterActive = false;
}
});
function handleEventAll(e) {
const test = e.target.querySelector(".head-dropdown");
test.classList.add("activated");
queue.unshift(test);
if (queue.length > 3) {
queue.pop();
}
dropdowns.forEach((val, i) => {
if (!val.dataset) {
val.dataset.isActivated = false;
}
let t = eval(queue[0].dataset.isActivated);
console.log(t);
if (t) {
console.log("in true", queue[0]);
queue[0].dataset.isActivated = true;
queue[0].classList.toggle("activated");
queue.pop();
} else {
console.log("in false", queue[0].dataset);
queue[0].dataset.isActivated = false;
console.log(queue);
queue[1].classList.remove("activated");
queue.pop();
}
});
}
window.addEventListener("click", e => {});
The elements are added to the queue and the queue sorts it out if previous element which was opened is properly closed and it opens a new element which is clicked. If the same element is clicked twice the queue closes the element but does not open it again until some other element is clicked.
Here is codepen for full experience: https://codepen.io/darioKolic/pen/eYdYzdy

I rewrote the handleEventAll function to make the required functionality without using a queue. check this
What I did is save the current state (is activated class exist or not) for clicked element, and then I remove all activated class from all element then add or remove the class activated depends on the old value.

Related

Close button popup doesn't work (JAVASCRIPT)

i'm trying to create a custom pupop in javascript, this is my first time with this.
I have a problem with the close button, the "x" target correctly the div to close, but doesn't remove the "active" class at click.
https://demomadeingenesi.it/demo-cedolino/
HTML CODE
<div class="spot spot-2">
<div class="pin"></div>
<div class="contenuto-spot flex flex-col gap-3">
<img class="chiudi-popup" src="img/chiudi.svg" />
[---CONTENT---]
</div>
</div>
</div>
JAVASCRIPT CODE
const tooltips = function () {
const spots = document.querySelectorAll(".spot");
spots.forEach((spot) => {
const contenuto = spot.querySelector(".contenuto-spot");
const pin = spot.querySelector(".pin");
spot.addEventListener("click", () => {
let curActive = document.querySelector(".spot.active");
let contActive = document.querySelector(".contenuto-spot.show");
const chiudiPopup = document.querySelector(".chiudi-popup");
spot.classList.add("active");
contenuto.classList.add("show");
if (curActive && curActive !== spot) {
curActive.classList.toggle("active");
contActive.classList.toggle("show");
}
chiudiPopup.addEventListener("click", () => {
spot.classList.remove("active");
contenuto.classList.remove("show");
});
});
});
const chiudiPopup = document.querySelector(".chiudi-popup");
chiudiPopup.addEventListener("click", () => {
spot.classList.remove("active");
contenuto.classList.remove("show");
});
What the code above does is adding an click listener, but it's inside another click listener, so all it's doing is adding an click listener on the first .chiudi-popup that removes .active and .show from the last spot element.
It's hard to see if this is correct, because you haven't given us enough to reproduce the problem, but I moved the code above outside the spot.addEventListener("click", () => { and instead of searching the whole document with const chiudiPopup = document.querySelector(".chiudi-popup"); the code nows only targets the .chuidi-popup element within the spot: const chiudiPopup = spot.querySelector(".chiudi-popup");
const tooltips = function() {
const spots = document.querySelectorAll(".spot");
spots.forEach((spot) => {
const contenuto = spot.querySelector(".contenuto-spot");
const pin = spot.querySelector(".pin");
spot.addEventListener("click", () => {
let curActive = document.querySelector(".spot.active");
let contActive = document.querySelector(".contenuto-spot.show");
spot.classList.add("active");
contenuto.classList.add("show");
if (curActive && curActive !== spot) {
curActive.classList.toggle("active");
contActive.classList.toggle("show");
}
});
// MOVED FROM THE CLICK LISTENER
const chiudiPopup = spot.querySelector(".chiudi-popup");
chiudiPopup.addEventListener("click", () => {
spot.classList.remove("active");
contenuto.classList.remove("show");
});
});
EDIT: I missed that you have the img.chiudi-popup inside your container, which will trigger both event listeners. I would honestly just simplify the code and always hide the container when clicking on it again. You can still have the img.chiudi-popup (close image) to make it easier for the users to understand that they can click on it.
const tooltips = function() {
const spots = document.querySelectorAll(".spot");
spots.forEach((spot) => {
const contenuto = spot.querySelector(".contenuto-spot");
const pin = spot.querySelector(".pin");
spot.addEventListener("click", () => {
let curActive = document.querySelector(".spot.active");
let contActive = document.querySelector(".contenuto-spot.show");
if (curActive !== spot) {
spot.classList.add("active");
contenuto.classList.add("show");
}
if (curActive) {
curActive.classList.remove("active");
contActive.classList.remove("show");
}
});

check if class exists on that page javascript

I have an index page and a dashboard, on the index I'm using typewriter and particlesjs on the index only, and on the dashboard I have a sidebar.
If I have all the code as-is, I get errors as the page is still looking for typewriter and particlesjs on all pages.
So I have attempted to wrap each section around an if so the plan is if that class or id exists on that page it will only render that JS. So I've created the following code.
edited code below based on groovy_guy's answer
document.querySelector('nav .toggle').addEventListener('click', e => {
document.querySelector('nav .hidden').classList.toggle('show')
});
let checkTypewriter = document.getElementById('typewriter');
if (checkTypewriter.length > 0) {
new Typewriter('#typewriter', {
strings: ['Website Developer', 'Freelancer' , 'System Admin'],
autoStart: true,
loop: true
});
}
let checkParticlesjs = document.getElementsByClassName('particlesjs');
if (checkParticlesjs.length > 0) {
let particles = Particles.init({
selector: '.particlesjs',
color: ['#48F2E3', '#48F2E3', '#48F2E3'],
connectParticles: true,
maxParticles: 200
});
}
let checkSidebar = document.getElementsByClassName('sidebar');
if (checkSidebar.length > 0) {
user_wants_collapse = false;
// Fetch all the details element.
const details = document.querySelectorAll("details");
// Add the onclick listeners.
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
// Close all the details that are not targetDetail.
details.forEach((detail) => {
if (detail !== targetDetail) {
detail.removeAttribute("open");
};
});
});
});
document.querySelector('section').addEventListener('click', (ev) => {
// close any open details elements that this click is outside of
let target = ev.target;
let detailsClickedWithin = null;
while (target && target.tagName != 'DETAILS') {
target = target.parentNode;
};
if (target && target.tagName == 'DETAILS') {
detailsClickedWithin = target;
};
Array.from(document.getElementsByTagName('details')).filter(
(details) => details.open && details != detailsClickedWithin
).forEach(details => details.open = false);
// if the sidebar collapse is true and is re-expanded by clicking a menu item then clicking on the body should re-close it
if (user_wants_collapse == true && (document.querySelectorAll('.sidebar details'))) {
document.querySelector('body').classList.add('is--expand');
};
});
// when the sidebar menu is clicked this sets the user_wants_collapse var to true or false and toggles is--expand class on body
document.querySelector('.sidebar .menu-link').addEventListener('click', () => {
document.querySelector('body').classList.toggle('is--expand');
user_wants_collapse = !user_wants_collapse
document.querySelector('.sidebar').classList.toggle('is--expand');
// show all text
document.querySelectorAll('.sidebar .title').forEach((el) => {
el.classList.toggle('hidden');
});
// changing sidebar menu items and menu collapse icons
const icon = document.querySelector('.menu-link-arrows span');
if (icon.classList.contains('fa-angle-double-left')) {
icon.classList.remove('fa-angle-double-left');
icon.classList.add('fa-angle-double-right');
} else {
icon.classList.remove('fa-angle-double-right');
icon.classList.add('fa-angle-double-left');
}
});
// making sure the sidebar menu items re-expands the sidebar on click
let x = document.querySelectorAll('.sidebar details');
let i;
for (i = 1; i < x.length; i++) {
x[i].addEventListener('click', () => {
// changing sidebar menu items and menu collapse icons
// change menu items and menu collapse icons
const icon = document.querySelector('.sidebar-drop-parent-arrow span');
if (icon.classList.contains('fa-chevron-down')) {
icon.classList.remove('fa-chevron-down');
icon.classList.add('fa-chevron-up');
} else {
icon.classList.remove('fa-chevron-up');
icon.classList.add('fa-chevron-down');
}
if (document.querySelector('body').classList.contains('is--expand')) {
document.querySelector('body').classList.remove('is--expand');
};
});
};
};
when loading the JS I'm not getting any console errors but I'm not seeing any result of the JS.
Why don't you use querySelector()? I think that's more uniform across your codebase. Besides, I see that you only care about one element and not a list of elements, so this method is ideal since it gets the first element that encounters.
const checkTypewriter = document.querySelector('#typewriter')
if (checkTypewriter) {
// Element with an ID 'typewriter' exist in the DOM.
}
const checkParticlesjs = document.querySelector('.particlesjs')
if (checkParticlesjs) {
// Element with a class named "particlesjs" exist in the DOM.
}
Also, make sure to check if an element exist before attaching an event listener:
const toggleNav = document.querySelector('nav .toggle')
if (toggleNav) {
toggleNav.addEventListener('click', (e) => {
document.querySelector('nav .hidden').classList.toggle('show')
});
}
For Javascript:
var checkTypewriter = document.getElementsByClassName('typewriter');
if (checkTypewriter.length > 0) {
// Here write your code
}
var checkParticlesjs = document.getElementsByClassName('particlesjs');
if (checkParticlesjs.length > 0) {
// Here write your specific code
}
For JQuery:
if ($("#typewriter")[0]){
// Here write your code
}
if ($(".particlesjs")[0]){
// Here write your specific code
}
This is how you can check if your classes exist,

Avoid numbers incrementing multiple times when calling a function multiple times

I have written a quantity selector function to display on a page. The page can open some modals, which need to have another quantity selector within each.
I am calling the function within the main page, and also within the modal (to enable the functionality once the modal is displayed.)
When I adjust the quantity in the modal, close the modal, and adjust the quantity on the main page, the quantity increments/decrements double (or 3 times if I was to call the function 3 times.)
Is there a way to "reset" each of these event listeners/functions, to only adjust for their respective elements?
I've looked into "removeEventListener" but haven't had any joy in implementing this within my code.
Example of my work so far here (you can see what I mean if you click the buttons.)
https://codepen.io/777333/pen/zYoKYRN
const quantitySelector = () => {
const qtyGroups = document.querySelectorAll('.qty-group');
if(qtyGroups) {
qtyGroups.forEach((qtyGroup) => {
const qtyDecrease = qtyGroup.querySelector('[data-quantity-decrease]');
const qtyIncrease = qtyGroup.querySelector('[data-quantity-increase]');
const qtyInput = qtyGroup.querySelector('[data-quantity-input]');
const disableEnableDecrease = () => {
if(qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
qtyDecrease.addEventListener('click', (event) => {
event.preventDefault();
if(qtyInput.value > 1) {
qtyInput.value--;
}
disableEnableDecrease();
});
qtyIncrease.addEventListener('click', (event) => {
event.preventDefault();
qtyInput.value++;
disableEnableDecrease();
});
qtyInput.addEventListener('keyup', () => {
disableEnableDecrease();
});
});
}
};
quantitySelector(); // called within main page
quantitySelector(); // called within modal
The issue at hand is that each time you're calling the function, a new event handler is added on top of the previous ones. The best way to avoid this is through Event Delegation where you add a global event handler only once.
// A global event handler
document.addEventListener(
"click",
function (event) {
// Find the qty-group if clicked on it
const qtyGroup = event.target.closest(".qty-group");
// Stop if the click was elsewhere
if (qtyGroup) {
// Get your elements
const qtyDecrease = qtyGroup.querySelector("[data-quantity-decrease]");
const qtyIncrease = qtyGroup.querySelector("[data-quantity-increase]");
const qtyInput = qtyGroup.querySelector("[data-quantity-input]");
const disableEnableDecrease = () => {
if (qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
// Match your elements against what was clicked on.
if (event.target == qtyDecrease) {
event.preventDefault();
if (qtyInput.value > 1) {
qtyInput.value--;
}
disableEnableDecrease();
}
if (event.target == qtyIncrease) {
event.preventDefault();
qtyInput.value++;
disableEnableDecrease();
}
}
},
false
);
Instead of listening to individual elements, you can capture all the clicks on the document, and then finding those that click on elements of interest. You can make a second event handler for the keyup event.
You can save the value of qtyInput on mousedown event and then in the increment you add or subtract one from the saved value instead of the current value of the input.
const quantitySelector = () => {
const qtyGroups = document.querySelectorAll('.qty-group');
if(qtyGroups) {
qtyGroups.forEach((qtyGroup) => {
const qtyDecrease = qtyGroup.querySelector('[data-quantity-decrease]');
const qtyIncrease = qtyGroup.querySelector('[data-quantity-increase]');
const qtyInput = qtyGroup.querySelector('[data-quantity-input]');
const disableEnableDecrease = () => {
if(qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
let savedValue = null;
const saveState = (evebt) => savedValue = Number(qtyInput.value);
qtyDecrease.addEventListener('mousedown', saveState)
qtyIncrease.addEventListener('mousedown', saveState)
qtyDecrease.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
if(qtyInput.value > 1) {
qtyInput.value = savedValue - 1;
}
disableEnableDecrease();
});
qtyIncrease.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
qtyInput.value = savedValue + 1;
disableEnableDecrease();
});
qtyInput.addEventListener('keyup', () => {
disableEnableDecrease();
event.stopPropagation();
});
});
}
};
quantitySelector();
quantitySelector();
There is a method called removeEventListener (MDN) but I suggest you to reshape your code such that you do not add event listener if they are already present.
Put all of your addEventListener just when you create your elements, or in a "document ready" callback if they are instantiated by HTML code. Then, when you open your modal, just update your values.
UPDATING YOUR CODE
// hide/show modal function
function toggleModal() {
let modal = document.getElementById('modal');
modal.style.display = modal.style.display == 'none' ? 'block' : 'none';
}
// your document ready function
function onReady() {
const qtyGroups = document.querySelectorAll('.qty-group');
if(qtyGroups) {
qtyGroups.forEach((qtyGroup) => {
const qtyDecrease = qtyGroup.querySelector('[data-quantity-decrease]');
const qtyIncrease = qtyGroup.querySelector('[data-quantity-increase]');
const qtyInput = qtyGroup.querySelector('[data-quantity-input]');
const disableEnableDecrease = () => {
if(qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
qtyDecrease.addEventListener('click', (event) => {
event.preventDefault();
if(qtyInput.value > 1) {
qtyInput.value--;
}
disableEnableDecrease();
});
qtyIncrease.addEventListener('click', (event) => {
event.preventDefault();
qtyInput.value++;
disableEnableDecrease();
});
qtyInput.addEventListener('keyup', () => {
disableEnableDecrease();
});
});
}
// attach hide/show modal handler
const toggle = document.getElementById('modal_toggle');
toggle.addEventListener('click', toggleModal);
}
onReady();
<div class="qty-group">
<button data-quantity-decrease disabled>-</button>
<input data-quantity-input value="1">
<button data-quantity-increase>+</button>
</div>
<div class="qty-group" id="modal" style="display: none;">
<button data-quantity-decrease disabled>-</button>
<input data-quantity-input value="1">
<button data-quantity-increase>+</button>
</div>
<button id="modal_toggle">Toggle Modal</button>
REFACTORING
It is better in such cases to reason as Components. Components ensure code encapsulation, maintainability, reusage, single responsability and many other usefull principles:
// hide/show modal function
function toggleModal() {
// get the modal
let modal = document.getElementById('modal');
// hide the modal
modal.style.display = modal.style.display == 'none' ? 'block' : 'none';
// reset the input of the modal
modalInputReference.reset();
}
function createQuantityInput(target, initialQuantity=1, min=1, max=10, step=1) {
let quantity = 0;
// assign and check if should be disable, also bind to input value
let assign = (q) => {
quantity = Math.max(Math.min(q, max), min);
decrease.disabled = quantity <= min;
increase.disabled = quantity >= max;
input.value = quantity;
};
// CREATION
// This part is not mandatory, you can also get the elements from
// the target (document.querySelector('button.decrease') or similar)
// and then attach the listener.
// Creation is better: ensure encapsulation and single responsability
// create decrease button
let decrease = document.createElement('button');
decrease.addEventListener('click', () => { assign(quantity - step); });
decrease.innerText = '-';
// create increase button
let increase = document.createElement('button');
increase.addEventListener('click', () => { assign(quantity + step); });
increase.innerText = '+'
// create input field
let input = document.createElement('input');
input.value = quantity
input.addEventListener('change', () => { assign(parseFloat(input.value)); });
// resetting the quantity
assign(initialQuantity);
// appending the new component to its parent
target.appendChild(decrease);
target.appendChild(input);
target.appendChild(increase);
// return a reference to manipulate this component
return {
get quantity() { return quantity; },
set quantity(q) { assign(q); },
assign,
reset: () => assign(initialQuantity)
};
}
// this will be your modal reference
let modalInputReference;
function onReady() {
// inject all qty-group with a "quantityInput" component
document.querySelectorAll('.qty-group').forEach(elem => {
let input = createQuantityInput(elem);
if (elem.id == 'modal') {
// if it is the modal I save it for later use
// this is just an hack for now,
// a full code should split this part into a "modal" component maybe
modalInputReference = input;
}
});
// emualte the modal
let toggle = document.getElementById('modal_toggle')
toggle.addEventListener('click', toggleModal)
}
// this function should be wrapped by a
// $(document).ready(onReady) or any other
// function that ensure that all the DOM is successfully loaded
// and the code is not executed before the browser has generated
// all the elements present in the HTML
onReady();
<div class="qty-group"></div>
<div class="qty-group" id="modal" style="display: none;"></div>
<button id="modal_toggle">Toggle Modal</button>
It is shorter (without comments) and also more maintenable. Don't trust who says it is overengineered, it is just kind of time to learn to reason this way, then is much easier and faster. It is just a time investment to waste less time in the future. Try figure out why React or Angular(JS) have climbed the charts of the best frameworks so fast.

How to prevent modal event listener from affecting other items?

I'm currently working on a Library app where a user can track unread and read books. I have it setup where when you click a book a modal pops up with the title, author, and buttons allowing you to mark the book as read or completely delete it.
I'm trying to fix a problem where opening and closing more than one modal and then clicking the delete button will delete all the items you previously clicked.
Here's the delete function -
Book.prototype.delete = function() {
myLibrary = myLibrary.filter((e) => {
return e !== this;
});
};
Here's how I'm opening each modal -
const render = () => {
const booksUnreadList = document.getElementById('unread');
const booksReadList = document.getElementById('read');
booksUnreadList.innerHTML = 'Unread';
booksReadList.innerHTML = 'Read';
myLibrary.forEach((book) => {
const li = document.createElement('li');
li.className = 'book';
book.read === 'Read'
? booksReadList.appendChild(li)
: booksUnreadList.appendChild(li);
li.innerHTML = book.info();
li.addEventListener('click', function handler() {
openBookModal(book);
});
});
And then the modal itself -
function openBookModal(book) {
document
.getElementById('book-modal-mark-complete')
.removeEventListener('click', markReadHandler);
document
.getElementById('book-modal-delete')
.removeEventListener('click', deleteHandler);
bookForm.style.display = 'none';
toggleForm.style.backgroundColor = '#978de0';
toggleForm.innerHTML = 'Add Book';
const bookModal = document.getElementById('book-modal');
bookModal.style.display = 'grid';
document.getElementById('book-modal-title').innerHTML = book.title;
document.getElementById('book-modal-author').innerHTML = 'By ' + book.author;
document
.getElementById('book-modal-mark-complete')
.addEventListener('click', markReadHandler);
function markReadHandler() {
book.read = 'Read';
render();
bookModal.style.display = 'none';
}
document
.getElementById('book-modal-delete')
.addEventListener('click', deleteHandler);
function deleteHandler() {
book.delete();
render();
bookModal.style.display = 'none';
}
document.getElementById('book-modal-close').addEventListener('click', () => {
bookModal.style.display = 'none';
});
}
Here's a jsfiddle of everything, to recreate the problem just open and close 2+ books and then delete 1 of them.
https://jsfiddle.net/Spawn_Bot/w6j4b8Lh/4/
Thanks!
You could store the currently selected book in the currentBook variable, move the modal event handlers outside the openBookModal() function and in the event handlers you could delete the currentBook:
let currentBook = {};
...
function openBookModal(book) {
currentBook = book;
...
}
document
.getElementById('book-modal-mark-complete')
.addEventListener('click', markReadHandler);
function markReadHandler() {
currentBook.read = 'Read';
render();
bookModal.style.display = 'none';
}
document
.getElementById('book-modal-delete')
.addEventListener('click', deleteHandler);
function deleteHandler() {
currentBook.delete();
render();
bookModal.style.display = 'none';
}
Here's the demo: https://jsfiddle.net/k6z08m2q/

Is this the correct format to write this? It's not working

I'm getting back to learning JavaScript and wondering why this isn't working. No errors are showing in the console.
I made it work with dry coding it but now I'm trying to not use dry and it's not working.
let simonLi = document.querySelector('#simon');
let simonPic = document.querySelector('#simon-pic');
let bruceLi = document.querySelector('#bruce');
let brucePic = document.querySelector('#bruce-pic');
let benLi = document.querySelector('#ben');
let benPic = document.querySelector('#ben-pic');
let pictureChange = pic => {
if (pic.className === "hide") {
pic.classList.remove("hide");
} else {
pic.classList.add("hide");
}
};
simonLi.addEventListener('click', pictureChange(simonPic));
bruceLi.addEventListener('click', pictureChange(brucePic));
benLi.addEventListener('click', pictureChange(benPic));
No error messages and it's suppose to hide and show the image whenever the li is click.
You are attaching the result of the function pictureChange (which happens to be undefined)to the click event, instead of attaching a function.
You can try replacing
let pictureChange = pic => {
if (pic.classList.contains("hide")) {
pic.classList.remove("hide");
} else {
pic.classList.add("hide");
}
};
With
let pictureChange = pic => {
return function() {
if (pic.className === "hide") {
pic.classList.remove("hide");
} else {
pic.classList.add("hide");
}
}
};
While your at it, consider using pic.classList.toggle() instead.
This might work better:
let simonLi = document.querySelector('#simon');
let simonPic = document.querySelector('#simon-pic');
let bruceLi = document.querySelector('#bruce');
let brucePic = document.querySelector('#bruce-pic');
let benLi = document.querySelector('#ben');
let benPic = document.querySelector('#ben-pic');
function pictureChange(pic) {
pic.classList.toggle('hide')
}
simonLi.addEventListener('click', function(e) {
pictureChange(simonPic)
});
bruceLi.addEventListener('click', function(e) {
pictureChange(brucePic)
});
benLi.addEventListener('click', function(e) {
pictureChange(benPic)
});
.hide {
color: red;
}
<div id="simon"><span id="simon-pic">Simon</span></div>
<br />
<div id="bruce"><span id="bruce-pic">Bruce</span></div>
<br />
<div id="ben"><span id="ben-pic">Ben</span></div>
This shortens your code sigificantly:
for (const li of document.querySelectorAll('li')) {
li.addEventListener('click', (event) => {
if (event.target.matches('li[id]')) {
document.getElementById(`${event.target.id}-pic`).classList.toggle('hide');
}
})
}
This assumes all your li work the way you've shown. Otherwise, give all those li a common CSS class, e.g. class="li-with-pic" and adjust the querySelector accordingly:
for (const li of document.querySelectorAll('.li-with-pic')) {
li.addEventListener('click', (event) => {
if (event.target.matches('.li-with-pic')) {
document.getElementById(`${event.target.id}-pic`).classList.toggle('hide');
}
})
}

Categories

Resources