Make WordPress Core

Changeset 49854


Ignore:
Timestamp:
12/21/2020 03:03:40 PM (3 years ago)
Author:
desrosj
Message:

Twenty Twenty-One: Allow local anchor links to be used in primary navigation.

This adds some JavaScript to detect when an anchor link is clicked within the primary navigation on mobile devices and closes the menu before scrolling to the location on the page.

Props poena, macmanx, t-p.
Fixes #52006.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-content/themes/twentytwentyone/assets/js/primary-navigation.js

    r49826 r49854  
    151151        } );
    152152
     153        /**
     154         * Close menu and scroll to anchor when an anchor link is clicked.
     155         * Adapted from TwentyTwenty.
     156         */
     157        document.addEventListener( 'click', function( event ) {
     158            // If target onclick is <a> with # within the href attribute
     159            if ( event.target.hash && event.target.hash.includes( '#' ) ) {
     160                wrapper.classList.remove( id + '-navigation-open', 'lock-scrolling' );
     161                twentytwentyoneToggleAriaExpanded( mobileButton );
     162                // Wait 550 and scroll to the anchor.
     163                setTimeout(function () {
     164                    var anchor = document.getElementById(event.target.hash.slice(1));
     165                    anchor.scrollIntoView();
     166                }, 550);
     167            }
     168        } );
     169
    153170        document.getElementById( 'site-navigation' ).querySelectorAll( '.menu-wrapper > .menu-item-has-children' ).forEach( function( li ) {
    154171            li.addEventListener( 'mouseenter', function() {
Note: See TracChangeset for help on using the changeset viewer.