Switching between font awesome icons

Marsi

New Member
#1
I'm trying to switch between icons using the unicode. I'm not sure what i'm doing wrong, I've tried switching using their className instead, that didn't work for me either, any answers are appreciated. (I would like to use vanilla javascript only no jquery)
Mã:
const burger = document.getElementById('toggle');

burger.addEventListener('click', (e) => {
  const tog = e.target;
  if (tog.innerHTML === "&#xf0c9") {
    nav.style.display = "flex";
    tog.innerHTML = "&#xf00d";
  } else {
    nav.style.display = "none";
  }

});
Mã:
<header class="navbar">
  <i class="fa" id="toggle">&#xf0c9</i>

  <nav class="menu">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Gallery</a>
    <a href="#">Contact</a>
    <a href="#">Search</a>
  </nav>
</header>
 

Admin

Administrator
Thành viên BQT
#2
You could do something like this:
Mã:
// fa-bars <-> fa-close

function toggleBetweenTwoClasses(el, c1, c2) {
  var currentClass = el.getAttribute("class");
  var newClass;
  if (currentClass.indexOf(c1) !== -1) {
    newClass = currentClass.replace(c1, c2);
    // Do stuff 1
  }
  if (currentClass.indexOf(c2) !== -1) {
    newClass = currentClass.replace(c2, c1);
    // Do stuff 2
  }
  el.setAttribute("class", newClass);
}

function myToggleBetweenTwoClasses(el, c1, c2) {
  toggleBetweenTwoClasses(document.getElementById("toggle"), "fa-bars", "fa-close");
}

var icon = document.getElementById("toggle");


icon.addEventListener("click", myToggleBetweenTwoClasses);
Mã:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

<header class="navbar">
  <i class="fa fa-bars" id="toggle"></i>
  <nav class="menu">
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Gallery</a>
    <a href="#">Contact</a>
    <a href="#">Search</a>
  </nav>
</header>
 
Top