Skip to content

Instantly share code, notes, and snippets.

@melissajclark
Last active March 19, 2024 19:23
Show Gist options
  • Save melissajclark/b3c7d008ed4cf3f98556f64fff1836af to your computer and use it in GitHub Desktop.
Save melissajclark/b3c7d008ed4cf3f98556f64fff1836af to your computer and use it in GitHub Desktop.
WordPress sub-menu JS: turn [a href="#"] links into <button> and more
<?php
/**
* Enqueue the JS file.
*
* @since 1.0.0
*
* @return void
*/
function clientname_styles_and_scripts() {
wp_enqueue_script(
'qwf-ld-scripts',
get_stylesheet_directory_uri() . '/assets/js/theme.js',
array( 'jquery' ),
filemtime( get_stylesheet_directory() . '/assets/js/theme.js' )
);
}
add_action( 'wp_enqueue_scripts', 'clientname_styles_and_scripts' );
jQuery(function ($) {
/** Desktop sub-menus: Transform a[href="#"] links to buttons */
$('#site-header .menu-item-has-children > a[href="#"]').each( function(i){
var emptyLink = this;
var emptyLinkText = $(this).text();
$(emptyLink).replaceWith( '<button class="button-link sub-menu-toggle">' + emptyLinkText + '</button>');
});
/** Desktop sub-menus: add classes for targeting states of the sub menus */
$('#site-header .menu-item-has-children .sub-menu-toggle').on('click', function(){
var parentMenuItem = $(this).parent();
$(parentMenuItem).toggleClass('sub-menu-parent__open');
$(parentMenuItem).find('.sub-menu').toggleClass('sub-menu__open');
$(parentMenuItem).find('.sub-menu-toggle').toggleClass('sub-menu-toggle-open');
});
});
@melissajclark
Copy link
Author

melissajclark commented Mar 19, 2024

PHP to Enqueue the JS file and JS example

About theme.js

  • First function: Improve to change WordPress menu links a[href="#"] into a <button> for better accessibility of the menu.
  • Second function: add classes to <button class="button-link sub-menu-toggle"> and <ul class="sub-menu"> on click of the <button>. I target these classes to style the menu when active and inactive.

About functions.php

Use the function in this file to enqueue the JS in theme.js in your WordPress theme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment