I am trying my best, with my limited knowledge of Javascript, to write plain Javascript for some buttons to achieve the following:
a) Click any button, like button1, and its content will be shown b) Click the same button again, and its content will be hidden c) Click a button (e.g. button1), then click another button (e.g. button2), and display button2's content while hiding the previously clicked button's content (button1).
However, I can only manage two out of these three steps:
For instance, let's say we have three buttons:
Scenario 1
In Scenario 1, I can achieve a) but not b) or c)
I can click button1 to show its content, then click button2 to open its content and hide the content of button1. However, I cannot click button2 again to hide its content, so all button contents remain hidden.
The code snippet is as follows:
Scenario 2
In Scenario 2, I can achieve a) and b) but not c)
In this code snippet, I can make each button show and hide its content when clicked once to reveal and clicked again to hide. Unfortunately, when clicking on another button while the first one is still open, the first one does not hide:
Ideal Scenario 3:
As stated at the start, what I aim to accomplish is a combination of Scenarios 1 and 2:
a) Click any button, like button1, and its content will be displayed b) Click the same button again, and its content will be hidden c) Click a button (e.g. button1), then click another button (e.g. button2), and display button2's content while also closing the previously opened button's content (button1).
I've attempted tweaking my JS code like below, but I seem to be getting conflicting results - perhaps 'clicked' is always true? Or maybe my use of !=
is incorrect (or both).
let Buttons = document.querySelectorAll(".button");
for (let button of Buttons) {
button.addEventListener('click', (e) => {
const x = e.target;
const y = document.querySelector(".clicked");
const z = (y != x);
const q = (x = y);
if (z) {
z.classList.remove("clicked");
}
if (q) {
q.classList.toggle("clicked");
}
x.classList.toggle("clicked");
})
}
Any assistance would be greatly appreciated, but please refrain from using jQuery. Thank you.