Change Background Colour as Page Scroll Without Jquery

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.

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>

Change background color using javaScript (no jQuery please)?

The toogle method (other answer) is really the best way to go. However, your code doesnt work because you cant access CSS with the style attribute unless the CSS is inline.

To get the CSS in JS you need to use the computed style.

var compStyles = window.getComputedStyle(element);
compStyles.getPropertyValue('background-color')

beware, it outputs colors in rgb format.

Changing background color on scroll

If you want to change the background color when a given section hits the top of the screen, you could try something like:

const colors = ['', 'lightCyan', 'darkSkyBlue', 'aquamarine', 'electricBlue']
const sections = [...document.getElementsByTagName('section')]
window.addEventListener('scroll', function () {
const scrollFromTop = window.pageYOffset
for (let i = 0; sections.length > i; i++) {
if (scrollFromTop <= sections[i].offsetTop) { document.body.className = colors[i] break }
}
})
@import url('https://fonts.googleapis.com/css?family=Roboto+Mono');
* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Roboto Mono', monospace;}
body { background-color: #E5E1EE; transition: 0.3s all;}
section { height: 100vh;}
h1 { margin: 15rem;}
.lightCyan { background-color: #DFFDFF;}
.darkSkyBlue { background-color: #90BEDE;}
.aquamarine { background-color: #68EDC6;}
.electricBlue { background-color: #90F3FF;}
<section><h1 id="first-h1">This site is an experiment on scroll effects</h1></section>
<section><h1 id="second-h1">I really hope this helps me learn vanilla JavaScript better</h1></section>
<section><h1 id="third-h1">I think it will honestly</h1></section>
<section><h1 id="fourth-h1">Or maybe it will frustrate me till the end of time</h1></section>
<section><h1 id="fifth-h1">Even if that does happen, I'll still keep trying</h1></section>

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");
}
});
});

Sticky menu changing color when scrolling down without jquery

As Keno mentioned, the position: inherit in your media query is over riding position: sticky.

But using position: sticky only makes "sticky" relative to the parent not to the window according to MDN (https://developer.mozilla.org/en-US/docs/Web/CSS/position)

A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

For you to achieve the desired behavior the you should use position: fixed which is according to MDN (https://developer.mozilla.org/en-US/docs/Web/CSS/position)

It is [the element] positioned relative to the initial containing block established by the viewport.

So your CSS should be

.main-nav-sticky {
background-color: white;
}

.main-nav {
margin-top: 100px;
position: fixed;
align-items: center;
justify-content: space-around;
top: 0;
left: 0;
display: flex;
height: auto;
width: 100%;
color: green;
}

And as for changing the color of the navbar when the user scrolls, you are going to need javascript to detect the scroll event and change the colors accordingly.

Change Background-color on scroll

Here is a simple way to do it:

HTML

<body onscroll="scroll()">
...
</body>

JavaScript

// HSL Colors
var colors = [
[0, 100, 50],
[113, 75, 25],
[240, 87, 40],
[328, 24, 40]
],

el = document.getElementsByTagName('body')[0], // Element to be scrolled
length = colors.length, // Number of colors
height = Math.round(el.offsetHeight / length); // Height of the segment between two colors

function scroll() {
var i = Math.floor(el.scrollTop / height), // Start color index
d = el.scrollTop % height / height, // Which part of the segment between start color and end color is passed
c1 = colors[i], // Start color
c2 = colors[(i+1)%length], // End color
h = c1[0] + Math.round((c2[0] - c1[0]) * d),
s = c1[1] + Math.round((c2[1] - c1[1]) * d),
l = c1[2] + Math.round((c2[2] - c1[2]) * d);
el.style['background-color'] = ['hsl(', h, ', ', s+'%, ', l, '%)'].join('');
}

Working example: http://jsbin.com/elolud/2/edit



Related Topics



Leave a reply



Submit