Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 class="hamburger-menu">
      <i class="fa-solid fa-bars"></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');
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="hamburger-menu">
  <i class="fa-solid fa-bars"></i>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading