Archived topic
Close navigation search when tapped outside
5 replies · Started by Mikko on December 22, 2020
Hi,
I would like the navigation search close when tapped outside of it.
I asked similar question regarding closing the mobile navigation.
https://generatepress.com/forums/topic/close-mobile-menu-when-click-tap-outside/
Tom then provided this code:
document.addEventListener( 'click', function( evt ) {
var openedMenu = openedMenu = document.querySelector( '.toggled .menu-toggle' ),
targetElement = evt.target; // clicked element
do {
if ( targetElement == openedMenu ) {
// This is a click inside. Do nothing, just return.
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while ( targetElement );
// This is a click outside.
openedMenu.click();
} );
Would it be possible to edit this code so that it applies to navigation search too or if separate code is required I wouldn't mind using it either.
Thank you!
Hi,
We can add in one for the search:
document.addEventListener( 'click', function( evt ) {
var searchForm = document.querySelector( '.nav-search-active' );
var openedSearch = openedSearch = document.querySelector( '.close-search' ),
targetElement = evt.target; // clicked element
do {
if ( targetElement == openedSearch || targetElement == searchForm ) {
// This is a click inside. Do nothing, just return.
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while ( targetElement );
// This is a click outside.
openedSearch.click();
} );
I've tested it along with Tom's code and it seems to be working on my end. It should work for yours as well.
Let us know.
Works like a charm! Thank you.
Nice one! Glad it worked for you. No problem. :)
Hi,
When I use this script (added with an element) my search menu does not open, any suggestions how to fix this?
This website: https://veendambeweegt.nl/
Hans
Hi there,
do you want to remove that script and ill look at an alternative method.