I am trying to init magento accordion and I want it to behave differently on mobile than on desktop.
In my case I cannot use a <script>
in the phtml with the javascript such as:
<script>
if ($(window).width() <= 480) {
$('#narrow-by-list').accordion(); // init with mobile params
} else {
$('#narrow-by-list').accordion(); // init with desktop params
}
</script>
For some reason maybe related to how the content is loaded, sometimes it works and sometimes it breaks.
So instead I am using the x-magento-init
that always seems to work fine:
<script type="text/x-magento-init">
{
"#narrow-by-list": {
"accordion": {
"openedState": "active",
"collapsible": true,
"active": <?php echo $this->helper('MagentoFrameworkJsonHelperData')->jsonEncode($activeArray); ?>,
"multipleCollapsible": true,
}
}
}
</script>
The problem with this method of initialization is that I cannot put the conditions I need to detect mobile resolution and set different accordion params.
What I want to do is on mobile set active
as false
and multipleCollapsible
as false
too so that way on desktop the accordion is always open and allows to open multiple items and on mobile it is closed by default and only allows to open one item at a time.
2
Answers
What I ended up doing after a lot of testing is customizing magento accordion component as following:
I opened the file located at
libwebmageaccordion.js
and I have customized it like this:And finally in the
phtml
calling it with the new options:Then cleared the static files cache and reloaded the page.
With this solution I could end up with the exact behavior needed.
You could do something like this: