eaesergio
eaesergio

Reputation: 3

Toggle icon symbol on click using js

In this menu, I'm trying to change the "+" symbol to "-" on click, but I don't know how to proceed. It will be a button that I'll change to custom icons later...

html

<header id="header">
      <div class="header-container">
        <p id="logo">Logo</p>
        <nav id="nav">
          <div id="btn-mobile">+</div>
          <ul id="menu">
            <li><a href="#">Sobre</a></li>
            <li><a href="#">Trabalhos</a></li>
            <li><a href="#">Carreiras</a></li>
            <li><a href="#">Contato</a></li>
          </ul>
        </nav>
      </div>
    </header>

js

const btnMobile = document.getElementById('btn-mobile');

function toggleMenu() {
  const nav = document.getElementById('nav');
  nav.classList.toggle('active');
}

btnMobile.addEventListener('click', toggleMenu);

thanks!

Upvotes: 0

Views: 698

Answers (2)

brk
brk

Reputation: 50291

You can use i and use css class to set the content of + or -

const btnMobile = document.getElementById('icon');

function toggleMenu() {
  if (btnMobile.classList.contains('icon-plus')) {
    btnMobile.classList.remove('icon-plus');
    btnMobile.classList.add('icon-minus')
  } else if (btnMobile.classList.contains('icon-minus')) {
    btnMobile.classList.remove('icon-minus');
    btnMobile.classList.add('icon-plus')

  }
}

btnMobile.addEventListener('click', toggleMenu);
.icon-plus:after {
  content: '+';
  cursor: pointer;
}

.icon-minus:after {
  content: '-';
  cursor: pointer;
}
<header id="header">
  <div class="header-container">
    <p id="logo">Logo</p>
    <nav id="nav">
      <div id="btn-mobile">
        <i id='icon' class="icon icon-plus"></i>
      </div>
      <ul id="menu">
        <li><a href="#">Sobre</a></li>
        <li><a href="#">Trabalhos</a></li>
        <li><a href="#">Carreiras</a></li>
        <li><a href="#">Contato</a></li>
      </ul>
    </nav>
  </div>
</header>

Upvotes: 0

Deepak Kamat
Deepak Kamat

Reputation: 1980

All you got to do is use innerText on your btn-mobile

const btnMobile = document.getElementById('btn-mobile');

function toggleMenu() {
  const nav = document.getElementById('nav');
  const btnMobile = document.getElementById('btn-mobile');
  nav.classList.toggle('active');
  btnMobile.innerText = '-';
  
}

btnMobile.addEventListener('click', toggleMenu);

or textContent, both does almost the same job, there's just some minor difference. Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText

MDN is a great place to learn these basic JS DOM method.

Upvotes: 1

Related Questions