Reputation: 75
i am trying to implement a feature on a menu that i am working on.When i scroll more than 50 pixels, let's say, i want to make the background color black, for example. Here is my code:
function myFunction() {
var x = document.getElementById("test");
if ( document.body.scrollTop > 50 || document.documentElement.scrollTop > 50 ) {
x.classList.toggle("change");
}
}
#test {
background-color: #d2d2d2;
height: 90px;
position: fixed;
top: 0px;
left: 0px;
}
.change {
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onscroll="myFunction()">
<div id="test">
<p>
Wow, this is some really nice text, now isn't it?
</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="demo">
Kachow, another text.
</div>
</body>
As you can see, the background colour won't change. If you look at the CSS rules, you can see that the extra colour is added, but crossed off (in FireFox). Would you know why?
JSFiddle Demo: https://jsfiddle.net/TakeDown/7djmqkzL/12/.
Thank you for your time!
Upvotes: 0
Views: 76
Reputation: 42746
The id selector has a higher specificity than a plain class selector. Meaning your class css won't override the id one. So you need to create a selector that has a higher specificity, and in your case just tag on the id selector:
#test.change {
background-color:black;
}
If you don't want to tie it to a particular id, you can tag on the element name instead to make the specificity higher
div.change {
background-color:black
}
Can read more about css selector specificity on MDN or in the spec at here
Demo
function myFunction() {
var x = document.getElementById("test");
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
x.classList.add("change");
} else {
x.classList.remove("change");
}
}
#test {
background-color: #d2d2d2;
height: 90px;
position: fixed;
top: 0px;
left: 0px;
}
#test.change {
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onscroll="myFunction()">
<div id="test">
<p>
Wow, this is some really nice text, now isn't it?
</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="demo">
Kachow, another text.
</div>
</body>
Upvotes: 2
Reputation: 36
If you want to get rid of graphical glitches don't use toggle
x.classList.toggle("change");
Instead, just set it to black when the scroll is 50
x.style.background = "black";
Upvotes: 0