0

I have customized the woocommerce search form using an expanding search bar tutorial. At the moment it opens and closes on click of the magnifying glass icon. Instead, I would like it to close when either, clicking anywhere outside the search field itself, or on commencement of scrolling.

<div class="container">
    <form role="search" method="get" class="woocommerce-product-search" action="<?php echo esc_url( home_url( '/' ) ); ?>">
        
        
        <label class="screen-reader-text" for="woocommerce-product-search-field-<?php echo isset( $index ) ? absint( $index ) : 0; ?>"><?php esc_html_e( 'Search for:', 'woocommerce' ); ?></label>
        
        
        <input type="search" id="woocommerce-product-search-field-<?php echo isset( $index ) ? absint( $index ) : 0; ?>" class="search-field" placeholder="<?php echo esc_attr__( 'SEARCH', 'woocommerce' ); ?>" value="<?php echo get_search_query(); ?>" name="s" onkeyup="buttonUp();" required/>
        
        <button type="submit" value="<?php echo esc_attr_x( 'Search', 'submit button', 'woocommerce' ); ?>" class="searchbox-submit"><?php echo esc_html_x( '', 'submit button', 'woocommerce' ); ?></button>
        
        <span class="searchbox-icon"><i class="fa fa-search" aria-hidden="true"></i></span>
        
        <input type="hidden" name="post_type" value="product" />
        
        
    </form>
</div>
jQuery(document).ready(function(){
            var submitIcon = jQuery('.searchbox-icon');
            var inputBox = jQuery('.search-field');
            var searchBox = jQuery('.woocommerce-product-search');
            var isOpen = false;
            submitIcon.click(function(){
                if(isOpen == false){
                    searchBox.addClass('searchbox-open');
                    inputBox.focus();
                    isOpen = true;
                } else {
                    searchBox.removeClass('searchbox-open');
                    inputBox.focusout();
                    isOpen = false;
                }
            });  
             submitIcon.mouseup(function(){
                    return false;
                });
            searchBox.mouseup(function(){
                    return false;
                });
            jQuery(document).mouseup(function(){
                    if(isOpen == true){
                        jQuery('.searchbox-icon').css('display','block');
                        submitIcon.click();
                    }
                });
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.