Reputation: 13886
I have this code to change the background color of an element (which works fine)
<script>
window.onscroll = function() {
if(document.body.scrollTop == 0) {
jQuery("header#main-header").css('background-color', 'red');
}
}
</script>
Problem is that I need to set the color to red only if the page scroll is between 0 and 100 and set the color to yellow if is bigger than 100.
I tried this in this page: http://temporal-1.d246.dinaserver.com/ but not working:
<script>
window.onscroll = function() {
if(document.body.scrollTop <= 99) {
jQuery("header#main-header").css('background-color', 'red');
}
if(document.body.scrollTop >= 100) {
jQuery("header#main-header").css('background-color', 'yellow');
}
}
</script>
Upvotes: 2
Views: 4217
Reputation: 395
A simple execution for changing an element when you scroll
$(function () {
$(document).scroll(function() {
var $nav = $("class name");
// $nav.height() can be changed to whatever height you want to start the change effect
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
Upvotes: 0
Reputation: 11
jQuery(document).ready(function(){
jQuery("body").css('background-color', 'red');
jQuery(window).scroll(function(){
if ( jQuery(document).scrollTop() <= 99 ) {
jQuery("body").css('background-color', 'red');
} else {
jQuery("body").css('background-color', 'yellow');
}
})
})
Upvotes: 1
Reputation: 36703
Well you need to calculate top
offset a little differently
window.onscroll = function() {
var doc = document.documentElement;
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
if(top <= 99) {
jQuery("header#main-header").css('background-color', 'red');
}
else {
jQuery("header#main-header").css('background-color', 'yellow');
}
}
Upvotes: 2