<?php

    // prevent direct file access
	if( !defined( 'ABSPATH' ) ) exit;

    add_action('wp_enqueue_scripts', 'pixe_enqueue_scroll_anchor_script', 99);
    function pixe_enqueue_scroll_anchor_script(){
        $general = get_option('pixe_general', array());

        if( !empty($general['smooth-anchor-scroll']) && $general['smooth-anchor-scroll'] == 'no' ){
            return;
        }

        ob_start();
        pixe_print_scroll_anchor_script();
        wp_add_inline_script('pixe-inline', ob_get_clean());
    }

    function pixe_print_scroll_anchor_script(){
?>
(function(){
    'use strict';

    function getTarget(hash){
        if( !hash || hash == '#' ) return null;

        try{
            hash = decodeURIComponent(hash);
        }catch(e){}

        return document.getElementById(hash.replace(/^#/, ''));
    }

    function isVisible(element){
        if( !element ) return false;
        return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
    }

    function getOffset(){
        var offset = 0;
        var adminBar = document.getElementById('wpadminbar');

        if( isVisible(adminBar) && getComputedStyle(adminBar).position == 'fixed' ){
            offset += adminBar.getBoundingClientRect().height;
        }

        return offset;
    }

    function scrollToTarget(target, updateHash){
        if( !target ) return false;

        var top = target.getBoundingClientRect().top + window.pageYOffset - getOffset();
        window.scrollTo({
            top: Math.max(0, top),
            behavior: 'smooth'
        });

        if( updateHash && history.pushState ){
            history.pushState(null, '', '#' + target.id);
        }

        return true;
    }

    function isSamePage(link){
        return link.origin == window.location.origin &&
            link.pathname.replace(/^\//, '') == window.location.pathname.replace(/^\//, '') &&
            link.search == window.location.search;
    }

    // on link clicked
    document.addEventListener('click', function(e){
        var link = e.target.closest? e.target.closest('a[href*="#"]'): null;
        if( !link || !link.hash || !isSamePage(link) ) return;

        var target = getTarget(link.hash);
        if( !target ) return;

        e.preventDefault();
        scrollToTarget(target, true);
    });

    // on load with hash
    window.addEventListener('load', function(){
        var target = getTarget(window.location.hash);
        if( !target ) return;

        setTimeout(function(){
            scrollToTarget(target, false);
        }, 1);
    });
})();
<?php
    }
