Magento 2 – Enable Show/Hide Functionality on Header Search

javascriptmagento-2.1magento2search

I've currently got the following phtml file in my theme:

Vender/Theme/Magento_Search/templates/form.mini.phtml

and the following js file inside of my theme as well:

Vender/Theme/Magento_Search/web/form-mini.js

I've done some changes to the form-mini.js trying to show and hide the search on a desktop site as well as the mobile side.

mediaCheck({
    //media: '(max-width: 768px)',
     entry: function () {
         this.isExpandable = true;
     }.bind(this),
         exit: function () {
         this.isExpandable = false;
         this.element.removeAttr('aria-expanded');
    }.bind(this)
});

So i commented out the media query to stop the script running on anything less than 768px but, nothing. On clicking the label the aria-expanded still doesn't toggle.

This is my first time looking at the search functionality, any help would be awesome.

Thanks

Best Answer

You need to specify the media parameter to the mediaCheck function:

mediaCheck({
    media: 'all',
    entry: function () {
        this.isExpandable = true;
    }.bind(this),
    exit: function () {
        this.isExpandable = false;
        this.element.removeAttr('aria-expanded');
    }.bind(this)
});

Setting it to all means that it will never switch to the desktop settings.

There are some CSS changes that need to be made it get the basic show/hide functionality. Copy vendor/magento/theme-frontend-blank/Magento_CatalogSearch/web/css/source/_module.less to your theme in {theme}/Magento_CatalogSearch/web/css/source/_module.less.

At line 211, we should remove this code:

.label {
    &:extend(.abs-visually-hidden-desktop all);
}

This will make the label element visible in desktop.

At line 227, remove this:

input {
    .lib-input-placeholder(@form-element-input-placeholder__color);
    margin: 0;
    padding-right: 35px;
    position: static;
}

now the input element will be hidden and will show when the label element is clicked in both mobile and desktop.

There are other CSS tweaks that you'll need to make to get it to look good, for example the rule that hides the input is at line 68 and does so by setting left: -300%;, however in desktop the input is still visible if the window is wide enough.