chainboost chainboost - 10 months ago 52
CSS Question

How to let Materialize use classes for dropdowns and not ID's?

I am using Materialize CSS ( for my new template in OpenCart and I'm creating the navigation bar right now. Of course for navigation bars I need a dropdown and I looked at the requirement for a dropdown button with this framework but it needs a unique ID to actually work.

<!-- Dropdown Trigger -->
<a class='dropdown-button btn' href='#' data-activates='dropdown1'>Drop Me!</a>

<!-- Dropdown Structure -->
<ul id='dropdown1' class='dropdown-content'>
<li><a href="#!">one</a></li>
<li><a href="#!">two</a></li>
<li class="divider"></li>
<li><a href="#!">three</a></li>

This won't work in OpenCart since it's loops through a set of PHP code and thus sets the same ID name to several menu items which has sub-categories in them.

How can I change the Javascript behind this to let it work with classes instead of ID's?


I believe this is the JS code that triggers the dropdown. As you see it searches for an ID

// Click handler to show dropdown
origin.unbind('click.' + origin.attr('id'));
origin.bind('click.'+origin.attr('id'), function(e){
if (!isFocused) {
if ( origin[0] == e.currentTarget &&
!origin.hasClass('active') &&
($('.dropdown-content').length === 0)) {
e.preventDefault(); // Prevents button click from moving window
if (curr_options.stopPropagation) {
// If origin is clicked and menu is open, close menu
else if (origin.hasClass('active')) {
$(document).unbind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'));
// If menu open, add click close handler to document
if (activates.hasClass('active')) {
$(document).bind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'), function (e) {
if (! && ! && (!origin.find( ) {
$(document).unbind('click.'+ activates.attr('id') + ' touchstart.' + activates.attr('id'));

} // End else

Answer Source

The thing is this ID search in materialze.css is inherent to the library and it kinda makes sense too because how else will the javascript know which dropdown to trigger with a button click right? What you can do as a workaround which I can think off is generate different ids for every dropdown menu you create on through the PHP loop. Assuming your generate dropdowns in every loop I can think of a very simple way of doing this. You can have a counter in your PHP loop and just replace the ID part of your php code with this loop variable each time. Hope this helps! Cheers!