Adam Bell
Adam Bell

Reputation: 1045

JS: Change ScrollTop to display browser widths

I have a script in my WordPress site (https://deganiagroup.com/} where clicking one of the navigation button provides a scroll to effect to the proper place on the screen. Because of a sticky header, I had to add a fixed scrollTop value, which either works right on desktop but not on mobile, or the other way around.

This is because the header's height changes depending on browser width because the header itself changes. So a fixed height doesn't really work here.

Can I expand this script to offer break points so the scrollTop value changes based on header height no matter what the browser width is?

This script was meant for Elementor page builders, but realistically it could be for anything involving scrolling on click.

Javascript:

add_action( 'wp_footer', function() {
    if ( ! defined( 'ELEMENTOR_VERSION' ) ) {
        return;
    }
    ?>
    <script>
        jQuery( function( $ ) {
            // Add space for Elementor Menu Anchor link
            $( window ).on( 'elementor/frontend/init', function() {
                elementorFrontend.hooks.addFilter( 'frontend/handlers/menu_anchor    /scroll_top_distance', function( scrollTop ) {
                    return scrollTop - 121; // Scroll to fixed value
                } );
            } );
        } );
    </script>
    <?php
} );

Upvotes: 1

Views: 370

Answers (1)

blex
blex

Reputation: 25634

You could calculate the height directly insite the function:

<script>
  jQuery(function($) {
    var $siteHeader  = $('#site-header');
    
    // Add space for Elementor Menu Anchor link
    $(window).on('elementor/frontend/init', function() {
      elementorFrontend.hooks.addFilter('frontend/handlers/menu_anchor    /scroll_top_distance', function(scrollTop) {
        return scrollTop - $siteHeader.height();
      });
    });
  });
</script>

Upvotes: 1

Related Questions