DEV Community

Paboda Hettiarachchi
Paboda Hettiarachchi

Posted on

Custom Toggle for mobile

Came across a situation where a mobile only toggle is required. So default Magento toggle and accodion functionality was not suitable.
So the following custom toggle was written.
Pay attention to the css trick to check if mobile or not without using jquery window width.

$(window).width()
Enter fullscreen mode Exit fullscreen mode

phtml file

<div class="nav-container" data-mage-init='{"Vendor_Module/js/toggle": {}}'>
    <div class="header">
        <h1>HEADER</h1>
    </div>
    <div class="list">
        CONTENT IS HERE
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

js file

define([
        'jquery',
    ], function($) {
        return function(config, element) {
            var list = $('.list', $(element));

            if (list.is(':hidden')) {
                var isMobile = true;
            }

            if (isMobile) {
                $('.header', $(element)).click(function(){
                    if (list.is(':hidden')) {
                        list.show();
                    } else {
                        list.hide();
                    }
                });
            }
        };
    }
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)