I'm trying to create a function to trigger actions depending on the current section showing on the viewport.
I've managed to track if a specific section is on the viewport using this great answer by DaniP
Trigger event when user scroll to specific element - with jQuery
Now I'm trying to store the current section as a value in a current_section
variable
var current_section = $('#1');
function SectionTracking(section) {
$(window).scroll(function() {
var hT = $(section).offset().top,
hH = $(section).outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop()
if (wS > (hT+hH-wH)){
console.log('yes');
section.addClass('active');
current_section = section;
}
});
}
SectionTracking($('#4'));
.event-background {
background: green;
height: 100vh;
border: 1px solid black;
}
.event-background.active {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Index">
<section class="Index-page">
<div class="event-background" id="1">
Section 1
</div>
<div class="event-background" id="2">
Section 2
</div>
<div class="event-background" id="3">
Section 3
</div>
<div class="event-background" id="4">
Section 4
</div>
<div class="event-background" id="5">
Section 5
</div>
<div class="event-background" id="6">
Section 6
</div>
<div class="event-background" id="7">
Section 7
</div>
<div class="event-background" id="8">
Section 8
</div>
</section>
</div>
Prototype: https://codepen.io/VictorSavas/pen/MWgZGoY
PS: among other actions, my main goal with this is to have a single fixed button that scrolls to the next section, i want to use the current_section
variable to scroll to the next one.
Thank you in advance