Ukrycie elementu kiedy wychodzi poza okno

0

Cześć, mam element na stronie, który chcę ukryć jeśli pozycja elementu będzie niższa niż 45px od górnej pozycji okna. Właściwość $(id).position().top cały czas 0 pokazuje.

    const id = "#product_info";
    const heroImage = "#hero_image";

    $(window).scroll(function () {
        let position = $(id).position().top;

        if (position < 45) {
            $(heroImage).fadeOut();
        } else {
            $(heroImage).fadeIn();
        }

        console.log(position);
    });
1

https://api.jquery.com/position/

The .position() method allows us to retrieve the current position of an element (specifically its margin box) relative to the offset parent (...) Contrast this with .offset(), which retrieves the current position relative to the document.

0

Rozwiązanie:

const cardId = "product_info";
    const heroImage = "#hero_image";
    const card = document.getElementById(cardId);

    $(window).scroll(function () {
        let distanceFromTop = card.getBoundingClientRect().top;

        if(distanceFromTop < 45) {
            $(heroImage).fadeOut();
        } else {
            $(heroImage).fadeIn();
        }
    });

1 użytkowników online, w tym zalogowanych: 0, gości: 1