Search code examples
javascripthtmlcssmaterialize

Toggle multiple MaterializeCSS icons without using an id selector


I don't have trouble toggling an icon on one element, but if it's multiple elements I'm not sure how to do it. For one element I would use an id selector, but with multiple elements, it would seem really tedious to have every element include an id.

For example, this is one of my floating buttons that has a toggable icon:

<a class="fixed-action-btn btn-floating btn-large" style=" id="expand2">

<i class="material-icons">unfold_more</i>

</a>

and this is the Javascript:

<script>
var button = document.getElementById("expand2");
var boolean = true;

button.onclick = function(){

if(boolean == true){

$(".btn-large").html('<i class="material-icons">unfold_less</i>');
                boolean = false;
} 

else if(boolean == false){

$(".btn-large").html('<i class="material-icons">unfold_more</i>');
                boolean = true;
}
}
</script>

I'm trying to figure out how to toggle the icon for multiple elements without the use of an id selector. Thanks in advance!


Solution

  • If you are using jQuery then the simplest solution would be to attach the click event to a class.

    <script>
    $('.btn-large').on('click', function() {
        var $icon = $(this).find('.material-icons');
        if($icon.text() === 'unfold_less') $icon.text('unfold_more');
        if($icon.text() === 'unfold_more') $icon.text('unfold_less');
    });
    </script>