I’m making a custom menu for mobile and am trying to get a search bar to slide up when the menu button is clicked.
I’ve pretty much managed to get it working using a combinaiton of Add Search Toggle Icon at End of Menu in WordPress, and Create a Custom Navigation Menu in WordPress Without Using Plugins but for some reason the toggle speed isn’t being applied.
Here’s what I have so far:
function my_custom_menu() {
register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}
add_action( 'init', 'my_custom_menu' );
add_filter('wp_nav_menu_items', 'wpb_add_search_toggle', 10, 2);
// Filter in Search Toggle to end of primary menu
function wpb_add_search_toggle($items, $args) {
$items_array = array();
while ( false !== ( $item_pos = strpos ( $items, '<li', 3 ) ) ) // Add the position where the menu item is placed
{
$items_array[] = substr($items, 0, $item_pos);
$items = substr($items, $item_pos);
}
$items_array[] = $items;
array_splice($items_array, 2, 0, '<li class="search search-wpb"><a class="search-icon"><i class="fas fa-search"></i></a><div style="display:none;" class="wpbsearchform">'. get_search_form(false) .'</div></li>'); // insert custom item after 2nd item one
$items = implode('', $items_array);
return $items;
}
function wpb_hook_javascript() {
?>
<script>
jQuery(document).ready(function($){
/* Search Menu */
$(".search-icon").click(function() {
$(".wpbsearchform").slideToggle(200);
});
$(document).keyup(function(e) {
// Ref /questions/3369593/how-to-detect-escape-key-press-with-pure-js-or-jquery
// Close search if esc key pressed
if (e.key == "Escape") {
$(".wpbsearchform").slideToggle(200);
}
});
});
</script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
The ‘.slideToggle(200)’ doesn’t work, I’ve also tried ‘.slideToggle(“slow”).
Trying to alter the transition speed with css has also been ineffective using the following:
.wpbsearchform form#searchform {
left: 0;
width: 100% !important;
position: fixed !important;
top: unset !important;
bottom: 60px;
background: url(/wp-content/uploads/2023/11/Mobile-Store-bottom-120-noresize.jpg);
background-position: center;
background-repeat: no-repeat;
background-position-y: top;
padding: 10px !important;
transition: all 200ms;
box-sizing: border-box;
height: 60px;
}
Any suggestions would be very much appreciated!