Last active
March 19, 2024 19:23
-
-
Save melissajclark/b3c7d008ed4cf3f98556f64fff1836af to your computer and use it in GitHub Desktop.
WordPress sub-menu JS: turn [a href="#"] links into <button> and more
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP to Enqueue the JS file and JS example
About
theme.js
a[href="#"]
into a<button>
for better accessibility of the menu.<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.