inject css with javascript code example
Example: inject css with javascript
let isScrolled = false;
window.addEventListener("scroll", () => {
if (window.scrollY < 800) {
let styleString1 = `body {background: silver;}`
const style1 = document.createElement('style');
style1.textContent = styleString1;
document.head.append(style1);
// console.log("style1: ", style1)
isScrolled = false;
console.log("not past 800px, isScrolled: ", isScrolled)
} else {
let styleString2 = `body {background: red;}`
const style2 = document.createElement('style');
style2.textContent = styleString2;
document.head.append(style2);
// console.log("style2: ", style2)
isScrolled = true;
console.log("past 800px, isScrolled: ", isScrolled)
}
});
console.log("isScrolled 3", isScrolled)