How do I change my background on scroll using CSS?
As others already said, Nop, you can't only with CSS
, but a little js code
can do it for you.
Ex.
jQuery(window).scroll(function(){
var fromTopPx = 200; // distance to trigger
var scrolledFromtop = jQuery(window).scrollTop();
if(scrolledFromtop > fromTopPx){
jQuery('html').addClass('scrolled');
}else{
jQuery('html').removeClass('scrolled');
}
});
And in your CSS file:
html {
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html {
background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg);
}
html.scrolled {
background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals_2.jpg);
}
So basically you are adding or removing a class to the HTML tag
at some distance from the top with javascript
(jQuery in this case)... and with CSS
, changing that image.
Now on.. you can apply some transitions to the image, or play with the code to made it slideToggle for example instead changing the class.... and many many other options.
Good luck
EDIT:
Fiddle example: http://jsfiddle.net/pZrCM/
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.
CSS/ jQuery change background on scroll
I think here is the answer that you are looking for,
JS
// when the user start scrolling
window.addEventListener('scroll',()=>{
// now call the background
const myBackground = document.getElementById('myBG');
// now the condition when the user start scrolling then change the color
if(window.pageYOffset > 400){
myBackground.classList.add("is-sticky");
myBackground.classList.remove("is-sticky2");
}
else if(window.pageYOffset > 200){
myBackground.classList.remove("is-sticky");
myBackground.classList.add("is-sticky2");
}
// when the header be in the top of the page that mean window.pageYOffset = 0 so
else{
myBackground.classList.remove("is-sticky");
myBackground.classList.remove("is-sticky2");
}
})
CSS you need to add those classes :
.is-sticky{ background-color: blue;}
.is-sticky2{ background-color: red; }
and ofc the header should have the Id that we used in js code
Need to change background color on scroll
I have checked your sharable Link and observed that already on the page scroll one class is added to the header and on scroll top, it removes also. "header--not-sticked" this class is added to your header while it is not scrolled and "header--is-sticked" this class is added to your header on-page is scroll. So you can easily apply your CSS using both classes, Hope so this will help you.
Also, you have used the wrong class name to add and remove class, you need to remove "." from the header and make it an element because on your website there is no "header" class to your header element. Try the below code
$(function() {
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$("header").addClass("active");
} else {
//remove the background property so it comes transparent again (defined in your css)
$("header").removeClass("active");
}
});
});
Change background-position horizontal transition for color on scroll jQuery/CSS
Following the link you shared, I'm using Scroll event and that's your ultimate goal from what I understand.
So we can use $(document).ready()
or $(window).on('load',..
to initiate with the first animation using the class .intro
.
Then depending on scroll direction we toggle between two classes .slideleft
and .slideright
.
If that's a confusing choice of class names you can call them Up and Down.
$(document).ready(function() {
$('.box').addClass('intro');
});
(function() {
var lastScroll = 0;
$(window).on('scroll', function() {
if ($(".box").is(".intro")) {
$('.box').removeClass('intro');
}
var activeScroll = $(this).scrollTop();
//We check the scroll direction
cond = Boolean(activeScroll > lastScroll);
//each background sliding effect follow it's scroll direction
$(".box").toggleClass('slideleft', cond); //DownScroll
$(".box").toggleClass('slideright', !cond); //UpScroll
lastScroll = activeScroll;
});
}());
.box {
width: 100%;
height: 200px;
display: inline-block;
background-size: 200% 200%;
transition: background-position 1s;
background-image: linear-gradient(to right, #ff5851 50%, #F8F8F8 50%);
background-position: left;
}
.intro {
background-position: 50%;
}
.slideleft {
background-position: left center;
}
.slideright {
background-position: center center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<div class="lorem">
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
<p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
</div>
Changing background color on scroll with javascript
I would have done it like this.
const sections = document.querySelectorAll('section')
document.addEventListener('scroll', () => {
sections.forEach(section => {
if(section.getBoundingClientRect().top <= document.body.scrollTop) {
document.body.style.background = section.dataset.color
}
})
})
body {
transition: background-color .2s ease;
}
section {
height: 100vh;
}
<section data-color="white"></section>
<section data-color="green"></section>
<section data-color="purple"></section>
<section data-color="yellow"></section>
<section data-color="blue"></section>
<section data-color="white"></section>
Related Topics
Hovering Over CSS Transition in Safari Lightens Certain Font Color
How to Make One Circle Inside of Another Using CSS
Font-Feature-Settings: What Is the Correct Syntax
Position Element Over Background Image. But the Bg Img Changes Size with the Window. CSS
What Is the Different Between Clearfix Hack and Overflow:Hidden VS Overflow:Auto
Multiple !Important Class Declarations and Precedence
Why Are My Descenders Being Cut Off When Using CSS @Font-Face
Add Prefixes to CSS Class Names Using Less or SASS
CSS Transitions with :Before and :After Pseudo Elements
Can't Style Text on Input Submit Button as Bold
Webpack Can Not Load Font File: Unexpected Token
How to Center a List with Bootstrap 4
Change Collapse Breakpoint in Bootstrap 3.0
Can Not Use Theme Color with Text or Bg
Ordering Wordpress Stylesheets
How to Make the Horizontal Scrollbar for a Div Always Appear Fixed on the Bottom of the Page