Search code examples
javascripthtmliconsmaterialize

how to dynamically change materialize.css icons


I have a bootstrap dropdown collapse. I use it as a dropdown megamenu . there is an icon that I want it changed by clicking on it. and I use materialize.css icons pack, so I have to change the text, not the class. I used this

    function ChangeIcon(){
      document.getElementById("icon-change").textContent="close";
}
<i onclick="ChangeIcon()" id="icon-change" data-toggle="collapse" data-target="#mega-menu-dropdown" class="material-icons">menu</i>
but the problem is, when I want to close it ,the icon doesn't change to its first type ( menu -> close and vice versa ). what should I do to solve this prob ?


Solution

  • function ChangeIcon(_this){
        if(_this.textContent === "close") {
            _this.textContent = "menu";
        } else {
            _this.textContent = "close";
        }
    }
    
    <i onclick="ChangeIcon(this)" id="icon-change" data-toggle="collapse" data-target="#mega-menu-dropdown" class="material-icons">menu</i>