0

In a nutshell I'm creating a sticky button that shows after the scroll position pass a target element on the page. I'm trying to calculate the distance from the top of the page to the bottom of the target element. The script below seems to work find on load but if I resize the browser the numbers are not recalculated to get the correct distance. I know I should be using another event listener like "on resize" but I can't seem to get the logic right with my current code. Any help is welcome thanks!

Current Code

$(function(){

    function ctaBundle(){
        //target element
        var cardsContainer = document.querySelector('.card-block');

        // calculate the distance from top to the bottom of target element plus padding offset
        var elDistanceToTop = window.pageYOffset + cardsContainer.getBoundingClientRect().bottom - 48;

        //using to only trigger on mobile using mql
        var mq = window.matchMedia('(max-width: 30em)');

        //function with if statement to fade in if you pass target element
        $(window).on('scroll', function() {
            if ($(this).scrollTop() > elDistanceToTop && mq.matches) {
                $(".sticky-cta-double").fadeIn();
            }else{
                $(".sticky-cta-double").hide();
            } 
        });   
    }
    ctaBundle();

});

Cedric W
  • 13
  • 5
  • https://stackoverflow.com/questions/9872128/get-bottom-and-right-position-of-an-element . you can use this to get element bottom and position, so when you get it, trigger your function to show/hide button – Armin Jan 28 '20 at 15:40

1 Answers1

0

I think I figured it out. By removing the on scroll event in the function and adding both event listeners after the function it seems to work.

$(function(){

    function ctaBundle(){
        var cardsContainer = document.querySelector('.card-block');
        var bundleHeader = document.querySelector('.bundle-header');
        var elDistanceToTop = window.pageYOffset + cardsContainer.getBoundingClientRect().bottom - 48;
        var mq = window.matchMedia('(max-width: 30em)');

        if ($(this).scrollTop() > elDistanceToTop && mq.matches) {
            $(".sticky-cta-double").fadeIn();
        }else{
            $(".sticky-cta-double").hide();
        } 
    }
    ctaBundle();
    window.addEventListener('resize', ctaBundle, false); 
    window.addEventListener('scroll', ctaBundle, false);

});

If anyone has a better answer/logic please let me know but this seems to be working as intended now.

Cedric W
  • 13
  • 5