Skip to content

Instantly share code, notes, and snippets.

@krogsgard
Last active November 2, 2018 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krogsgard/6386511 to your computer and use it in GitHub Desktop.
Save krogsgard/6386511 to your computer and use it in GitHub Desktop.
jQuery for handling toggle functionality with wp_localize_script ( small_menu_vars.size ) and WordPress.
<?php
/**
* krogs_child_theme_new_menu_size function.
*
*/
add_filter( 'krogs_theme_small_menu_size', 'krogs_child_theme_new_menu_size' );
function krogs_child_theme_new_menu_size( $size ) {
$size = 450;
return 450;
}
<?php
/**
* Registers scripts for the theme and enqueue those used sitewide.
*
* @since 0.1.0.
*/
add_action( 'wp_enqueue_scripts', 'krogs_theme_scripts' );
function krogs_theme_scripts() {
wp_register_script( 'small-menu', get_template_directory_uri() . '/js/small-menu.js', array( 'jquery' ), '20120206', true );
wp_localize_script('small-menu', 'small_menu_vars', array(
'size' => apply_filters( 'krogs_theme_small_menu_size', 600 )
)
);
wp_enqueue_script( 'small-menu' );
}
/**
* Handles toggling the main navigation menu for small screens.
* small_menu_vars.size is used instead of "600" or other hard coded pixel value - it is defined by wp_localize_script in functions
*/
jQuery( document ).ready( function( $ ) {
var $masthead = $( '#masthead' ),
timeout = false;
$.fn.smallMenu = function() {
$masthead.find( '.site-navigation' ).removeClass( 'main-navigation' ).addClass( 'main-small-navigation' );
$masthead.find( '.site-navigation h1' ).removeClass( 'assistive-text' ).addClass( 'menu-toggle' );
$( '.menu-toggle' ).click( function() {
$masthead.find( '.menu' ).toggle();
$( this ).toggleClass( 'toggled-on' );
} );
};
// Check viewport width on first load.
if ( $( window ).width() < small_menu_vars.size )
$.fn.smallMenu();
// Check viewport width when user resizes the browser window.
$( window ).resize( function() {
var browserWidth = $( window ).width();
if ( false !== timeout )
clearTimeout( timeout );
timeout = setTimeout( function() {
if ( browserWidth < small_menu_vars.size ) {
$.fn.smallMenu();
} else {
$masthead.find( '.site-navigation' ).removeClass( 'main-small-navigation' ).addClass( 'main-navigation' );
$masthead.find( '.site-navigation h1' ).removeClass( 'menu-toggle' ).addClass( 'assistive-text' );
$masthead.find( '.menu' ).removeAttr( 'style' );
}
}, 200 );
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment