Changing background color of div on scroll
You need to bind your scroll event to your div
with id="left-panel"
, because that's the element that has the scrollbar on it (i.e. the element with overflow: auto
and a child element larger than itself).
Binding to document
or window
won't work, because in this case they are not the element with the scrollbar.
Working Live Demo:
$(document).ready(function () { var scroll_pos = 0; $("#left-panel").scroll(function () { scroll_pos = $(this).scrollTop(); if (scroll_pos > 210) { $("#left-panel").css('background-color', '#1A1A1A'); } else { $("#left-panel").css('background-color', 'red'); } console.log(scroll_pos); });});
#left-panel { position: fixed; top: 0; left: 0; width: 80%; height: 100%; z-index: 2; overflow:auto; height:2000px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div id="left-panel"> <div style="height:5000px;">CONTENT</div></div>
Change div background color on scroll
TL;DR, Here is a working js code:
window.addEventListener("scroll", scrollnav);
function scrollnav() {
var y = window.scrollY;
if (y > 1) {
document.getElementById("navbar").style.backgroundColor = "blue";
} else {
document.getElementById("navbar").style.backgroundColor = "unset";
}
}
Now let's dive into some educational details:
Simply, your JS function doesn't run. You can confirm that by using console.log
inside the method and watch the console.
First of all, although it has nothing to do with your problem, there is no scroll
attribute, but there is an onscroll
attribute.
Even if you use onscroll
nothing will change. Because when you scroll the page you don't scroll your #navbar
element, you scroll the whole window
so you can remove the method call from your element and add the correct event listener in your JS file:
window.addEventListener('scroll', scrollnav)
Once you confirm your function runs, you will have more meaningful error messages in your console.
To get the top possition, document.body.scrollTop()
is not a function so you can't call it. I suggest you use window.scrollY
for best results.
Last but not least, the CSS background-color
attribute doesn't have a value of none
, use unset
or initial
instead.
Notes:
- even if you add
window.addEventListener
before your function definition, it will still work because of hoisting - listening to the window scroll event is a costly operation, you should consider throttling or denouncing depending on the application, but it's out of the scope of question
Dynamically change background color on scroll
You need to smoothly interpolate the colors by taking into account the page's scroll offset (window.scrollY
, or window.pageYOffset
on older browsers).
The Samsung site is transitioning a solid color instead of a gradient, which is a bit simpler.
Like this (see CodePen):
const [red, green, blue] = [69, 111, 225]
const section1 = document.querySelector('.section1')
window.addEventListener('scroll', () => {
let y = 1 + (window.scrollY || window.pageYOffset) / 150
y = y < 1 ? 1 : y // ensure y is always >= 1 (due to Safari's elastic scroll)
const [r, g, b] = [red/y, green/y, blue/y].map(Math.round)
section1.style.backgroundColor = `rgb(${r}, ${g}, ${b})`
})
You can apply the same logic to the gradient colors.
Change div color when scrolling to a specific div class
If I Understand your question , The first condition check the would be offsettop - height
of your div , and the second there where an error in condition (condition iversion) ,
also adding the transition to you .background-overlay
instead of .black will have effect in both scroll up down
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var $divBlack = $('.background-overlay');
if (scroll >= $divBlack.offset().top - $divBlack.height()) { // check the offset top
$divBlack.addClass("black");
} else if (scroll <= $divBlack.offset().top + $divBlack.height()) { // check the scrollHeight
$divBlack.removeClass("black");
}
});
});
.full-height,
.page {
height: 500px;
border-bottom: 1px solid black;
}
.black {
background: #000000;
}
.background-overlay {
transition: background-color 2s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
</div>
<section class="full-height background-overlay">
</section>
<div class="page">
</div>
Change CSS background color when DIV in viewport
Explanation
"When the user scrolls to the TOP of the blue div, the background color of the body changes to red."
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= $('#blue').offset().top) {
$('body').css('background-color', 'red');
}
if (scroll >= $('#black').offset().top) {
$('body').css('background-color', 'blue');
}
if (scroll >= $('#black').last().offset().top) {
$('body').css('background-color', 'green');
}
});
#blue {
width: 400px;
height: 800px;
background: blue;
}
#black {
width: 400px;
height: 800px;
background: black;
}
#red {
width: 400px;
height: 800px;
background: red;
margin-bottom: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blue"></div>
<div id="black"></div>
<div id="red"></div>
Related Topics
Center an Image Vertically and Horizontally Using CSS
React - Prevent Event Trigger on Parent from Child
Getcomputedstyle (Or) $.Css(Map) <-- to Get Every Style Declaration
Changing Background Color of Div on Scroll
Ruby on Rails - Put Method on Update Ajax
How to Get JavaScript Caller Function Line Number and Caller Source Url
Declaring JavaScript Object Method in Constructor Function VS. in Prototype
Sending Message from a Background Script to a Content Script, Then to a Injected Script
How to Avoid Global Variables in JavaScript
Can JavaScript Access a Filesystem
Getelementsbyclassname to Change the Style of Elements When Event Occurs
Jquery to Change Style Attribute of a Div Class
Interrupting/Stop a CSS3 Transition on the Actual Position/State
How to Create Dynamic Elements Inside Global Tabs
Parsing JavaScript Using Ruby Code
Why Is String Concatenation Faster Than Array Join
How to Use JavaScript Source Maps (.Map Files)
After Travelling Back in Firefox History, JavaScript Won't Run