How to add a custom dropdown menu in Magento2 to a PHTML template
UPDATE June 2020
This answer is old and now Magento has better docs which describe how this can be done.
Please check: https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/widgets/widget_dropdown.html
In the end I got it working with the below:
<ul class="quick-links">
<li class="links-container">
<span data-mage-init='{"dropdown":{}}' data-toggle="dropdown">About</span>
<div class="customer-menu" data-target="dropdown">
<ul class="header links">
<li><a href="/contacts">Link 1</a></li>
<li><a href="/contacts">Link 2</a></li>
<li><a href="/contacts">Link 3</a></li>
</ul>
</div>
</li>
</ul>
I'm not sure why the example I gave in my question did not work as it's in all the answers on magento.stackexchange and is also what is outlined in the docs at lib/web/css/docs/dropdowns.html
The parent li
of the dropdown link needs to have a class of links-container
which I discovered just by looking through the Magento core by trial and error.
The dropdown menu opens on click only, next I would like to be able to change it to open on hover, I think I need to extend lib/web/mage/dropdowns.js for that.
UPDATE
I figured out why it wasn't working with the example in the docs, it was just that the CSS wasn't added to the HTML class example-dropdown-2
but the actual JavaScript is working. If you look at the HTML in the browser inspector you can see that the class active
is added to the ul
etc. For instance when you log in the the customer menu dropdown has this CSS
.customer-welcome .customer-menu {
display: none;
}
And .example-dropdown-2 .dropdown
does not. So you have to add your own CSS to hide & display the dropdown etc, or use the example I gave in my answer above which already has CSS if your theme inherits from the Luma them (maybe it's the same for the blank theme).
Shame, it's actually a really simple solution if the docs had been clearer it would have saved a lot of time. Although I should have spotted why it wasn't working sooner.