Im trying to change the color of my burger bar lines. I used an eventlistener and I try to target the spans that make up the burgermenu lines, by giving the span a class "span". as u can see here
var distFromTop = document.querySelector(".om-mux").offsetTop;
var distFromTop2 = document.querySelector(".galleri").offsetTop;
var distFromTop3 = document.querySelector(".event-sektion").offsetTop;
window.addEventListener("scroll", function() {
var scroll = this.scrollY;
if (scroll > distFromTop && scroll < distFromTop2) {
document.querySelector(".span").style.backgroundColor = "black";
} else if (scroll > distFromTop2 && scroll < distFromTop3) {
document.querySelector(".span:before").style.backgroundColor = "white";
} else if (scroll > distFromTop3){
document.querySelector(".span").style.backgroundColor = "black";
} else {
document.querySelector(".span").style.backgroundColor = "white";
}
})`
The code runs well, but problem is that this only affects the middle span, because of the fact that the upper and bottom line are styled as such:
` .menu-btn > span,
.menu-btn > span::before,
.menu-btn > span::after {
display: block;
position: absolute;
width: 100%;
height: 2px;
background-color: #ffffff;
transition-duration: .25s;
}`
How do I target span:before & span:after? can I do something like this? document.querySelector(".span:before").style.backgroundColor = "white";
CodePudding user response:
English is not my first Language so please bear with me. Try adding new class to span when you scroll and give that class background-color property in your CSS file. Example
Instead of this
document.querySelector(".span").style.backgroundColor = "black";
Try
document.querySelector(".span").classList.add('black');
and add this class css property in your css file.
.menu-btn > span.span.black::before{
background-color: #000;
}
CodePudding user response:
reference: Changing CSS pseudo-element styles via JavaScript
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
javascript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');