Basic info:
I have 4 sections, each section height = 100vh.
And a function that prints True to the console when reaching a half section height before section2, till section2 bottom reaches the top of the page (which means scrolling over it).
What I'm trying to achieve:
Animate an element with jQuery this way:
x will start as 1 and ends at 2, vice versa, in 10 steps, each step is 0.1
if (true) {
$(element).css({
transform: "scale(x)",
}, 500, 'easeInOutSine');
}
else {
$(element).css({
transform: "scale(x)",
}, 500, 'easeInOutSine');
}
So I have to convert the height of scrolling (number) from the start to the end, into a 10 step, every 1/10 of scrolling it adds 0.1.
In math, it looks like this (without the other half of section1):
var section = $(".section2");
var section_height = section.height();
var one_of_ten = section_height / 10;
var count = 0;
var x = 1;
while(x <= 2){
count = 0;
while(count <= one_of_ten){
count++;
}
x+=0.1;
}
It prints to the console the numbers from 1 to 2 in 10 steps.
The problem:
How can I get the height of the scrolling part and check for every 1/10 step to add 0.1 to x?
My Code:
function check_onscroll(){
var section = $(".section2");
var sectionHeight = section.height();
var sectionTop = section.offset().top;
$(window).scroll(function () {
var scrollFromTop = $(window).scrollTop();
if (sectionTop - ($(window).height() / 2) <= scrollFromTop
&& scrollFromTop <= sectionTop + section.height()){
console.log("True");
}
});
}
check_onscroll();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
height: auto;
}
.section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.section1 {
background-color: red;
}
.section2 {
background-color: yellow;
}
.section3 {
background-color: green;
}
.section4 {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section section1">
<h2>Section 1</h2>
</div>
<div class="section section2">
<h2>Section 2</h2>
</div>
<div class="section section3">
<h2>Section 3</h2>
</div>
<div class="section section4">
<h2>Section 4</h2>
</div>