Smithy
Smithy

Reputation: 847

Toggle Material Design icon button on click

I'm looking for a non-jQuery way of hiding & showing a Material Design icon button when toggling. Not sure if I should do it using innerHtml or something else. Let's say I'm trying to replicate jQuery's hide & show methods. Any help much is appreciated.

class ToggleMe {
  constructor() {
    this.toggleStar = document.querySelector(".iconStar")
    this.togglePhone = document.querySelector(".iconPhone")
    this.toggleMe = document.querySelector(".toggle-me")
    this.events()
  }

  events() {
    this.toggleStar.addEventListener("click", () => this.toggleColor())
  }

  toggleColor() {
    this.toggleMe.classList.toggle("toggle-me--blue")

    // change icon from Phone to Star and reverse
    // like jquery $(.iconStar).hide() / show()
  }
}
.toggle-me {
  background: red;
}

.toggle-me--blue {
  background: blue;
}
<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div class="toggle-me">
  <button class="mdc-icon-button material-icons iconStar">star</button>
  <button class="mdc-icon-button material-icons iconPhone">phone</button>
</div>

Upvotes: 0

Views: 912

Answers (1)

pretzelhammer
pretzelhammer

Reputation: 15115

You can bind an event handler to toggle a class on the icons which switches which one is visible and which on is hidden like this:

class ToggleMe {
  constructor() {
    this.toggleStar = document.querySelector(".iconStar")
    this.togglePhone = document.querySelector(".iconPhone")
    this.toggleMe = document.querySelector(".toggle-me")
    this.events()
  }

  events() {
    this.toggleMe.addEventListener("click", () => this.toggleColor());
  }

  toggleColor() {
    this.toggleMe.classList.toggle("toggle-me--blue")

    // toggle icon visibility here
    this.toggleStar.classList.toggle("hidden");
    this.togglePhone.classList.toggle("hidden");
  }
}

let toggleMe = new ToggleMe();
.toggle-me {
  background: red;
}

.toggle-me--blue {
  background: blue;
}

/* add this class to hide icon */
.mdc-icon-button.hidden {
  display: none;
}
<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<div class="toggle-me">
  <button class="mdc-icon-button material-icons iconStar">star</button>
  <button class="mdc-icon-button material-icons iconPhone hidden">phone</button>
</div>

Upvotes: 1

Related Questions