A
A
Alexander Timofeev2018-06-08 18:08:49
JavaScript
Alexander Timofeev, 2018-06-08 18:08:49

How to change the color of an element when crossing screens (when scrolling)?

Required for javascript.
Let's say the template looks like this:

<div id="block"></div>
<section></section>
<section></section>
<section></section

#block 100 by 100 px wide and long with position:stinky (i.e. it's like fixed). And sections by height=100hv. We want #block to change background color when it crosses section's.
5b1a9bf9e0ee9809154619.png

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
Oscar Handsome, 2018-06-08
@oscarhandsome

Hello, I have done such things through.
Finding coordinates in js
If there are better options, I'm ready to listen too.

A
Aleksey Solovyev, 2018-06-08
@alsolovyev

It is done by analogy with the stick menu . Just add a few conditions.
You need to know:
1) The value of the sections relative to the top of the page:
topPos = element.offsetTop
2) The height of the sections:

h = document.getElementById('A').clientHeight ||
h = document.getElementById('A').offsetHeight ||
h = document.getElementById('A').scrollHeight ||

3) Scroll position: Track the onscroll event Make a condition: If t is between topPos(section A value) and topPos(section A value) + h(section A value), then change the class If t is between topPos(section B value) and topPos( value of section B) + h(value of section B), then we change the class .... To load an empty processor, it is better to add debounce'r for onscroll Or use ready-made libraries: ScrollReveal Scrollmagic/ There are many of them. Choose which one suits you best. Here you will need to correct the indentation at which your event should fire. And, perhaps, the event itself (for this is usually an appearance, and you have a class change)

R
Ridz, 2018-06-08
@Ridz

Alexander Timofeev
Class change when scrolling

D
Dmitry Belyaev, 2018-06-08
@bingo347

Something like this, I think you will finalize it for yourself:
https://jsfiddle.net/bingo347/mxgr2vet/
IntersectionObserver doc: https://developer.mozilla.org/en/docs/Web/API/Inte... Polyfill
(no native in safari and ie): https://github.com/w3c/IntersectionObserver/blob/m...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question