Site logo

[Support request] Close navigation search when tapped outside

Home Forums Support [Support request] Close navigation search when tapped outside

Home Forums Support Close navigation search when tapped outside

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1591249
    Mikko

    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!

    #1591449
    Elvin
    Staff
    Customer Support

    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.

    #1592529
    Mikko

    Works like a charm! Thank you.

    #1596065
    Elvin
    Staff
    Customer Support

    Nice one! Glad it worked for you. No problem. 🙂

    #2398293
    Hans

    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

    #2399598
    David
    Staff
    Customer Support

    Hi there,

    do you want to remove that script and ill look at an alternative method.

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.