Home > Net >  How to swap between font awesome icons on the click of a button using plain JS?
How to swap between font awesome icons on the click of a button using plain JS?

Time:07-21

I created a font-awesome-bars icon button and upon being clicked will show a menu. Apart from that, I also want the font-awesome-bars icon to be replaced by a cross icon. I tried to use toggle but it doesn't work, with the console saying there shouldn't be space characters. But if I remove space characters, the document will not be able to read font awesome icons. Please, help me in this. Thanks you in advance.

<div >
      <i ></i>
    </div>

const hamburgerMenuBtnContainer = document.querySelector('.hamburger-menu');
const hamburgerMenuBtn = document.querySelector('.hamburger-menu i');

hamburgerMenuBtnContainer.addEventListener('click', function(){
   hamburgerMenuBtn.classList.toggle('fa-solid fa-xmark');
});

CodePudding user response:

const hamburgerMenuBtnContainer = document.querySelector('.hamburger-menu');
const hamburgerMenuBtn = document.querySelector('.hamburger-menu i');

hamburgerMenuBtnContainer.addEventListener('click', function() {
  hamburgerMenuBtn.classList.toggle('fa-xmark');
  hamburgerMenuBtn.classList.toggle('fa-bars');
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<div >
  <i ></i>
</div>

  • Related