I want to know how to keep the effect on my web page even if the page is refreshed.
My JS Code:
const button = document.querySelectorAll(".btn");
button.forEach((color) => {
color.style.backgroundColor = color.getAttribute("data-color");
color.addEventListener("click", () => {
const data = color.getAttribute("data-color");
const root = document.querySelector(":root");
const styles = {
"--bs-primary-rgb": data,
};
for (const [property, value] of Object.entries(styles)) {
root.style.setProperty(property, value);
}
});
});
What does this code do?
This code selects all elements with a class of btn
and then applies a click event listener to each of them. When one of the buttons is clicked, it gets the value of the data-color attribute and sets it as the value of the --bs-primary-rgb
CSS variable on the root element.
The querySelectorAll
method returns a static (not live) NodeList of elements that match the specified CSS selector. The forEach
method is used to iterate over the elements in the NodeList and apply the desired style changes to each element. The style
property of an element is an object that represents the inline style of the element, and the setProperty
method is used to set the value of a specific CSS property on that style object.
The getAttribute
method is used to retrieve the value of the specified attribute of an element. In this case, the value of the data-color
attribute is retrieved and used to set the value of the --bs-primary-rgb
CSS variable.
Check the full app in codepen:
Via Active questions tagged javascript - Stack Overflow https://ift.tt/YEZ2VX8
Comments
Post a Comment