R
R
rabodis2021-06-23 13:28:19
JavaScript
rabodis, 2021-06-23 13:28:19

How to track scrolling outside the block in js?

When the user moves the mouse over the box block, elem takes on the active class, but if within this block the page starts scrolling up and down, the element class does not change. Tell me how to track the scroll outside the block so that the class of the element changes when the user scrolls the page below or above the box?

<div class="box">
        <div class="elem active"></div>
</div>


.box{
    margin-top: 300px;
    width: 100%;
    height: 600px;
}

.elem{
    width: 100px;
    height: 120px;
    background: blue;
}

.active{
    background: red;
}


let parent = document.querySelector('.box'),
        element = document.querySelector('.elem'),
        k = parent.getBoundingClientRect();
        console.log(k);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Volkov, 2021-06-23
@rabodis

Here's a function that calculates coordinates relative to the document:

const coordinateCalculation = (e) => {
    coordinateQuote = coordinateQuote.push((Math.floor(element.getBoundingClientRect().top + window.pageYOffset)) - window.screen.height); // Добавляет в массив координаты элемента относительно документа=

    return coordinateQuote;
}

Then add a scroll event:
$(window).on('scroll', ( ) => {
    if(window.pageYOffset > 200) {

    } else if(window.pageYOffset < 200){

    }
})

p.s. jquery is used here.
Substitute the coordinates of your block instead of 200

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question