remove addEventListener for font-weight – Javascript

Advertisements

I created javascript eventListener by using javascript for my dropdown link. When I click on ‘bold’, everything turn bold. It is ok for me but I want to remove it when clicking. When I click again, my removeListener does not work, it is missing something I guess.

Thank you in advance.

//HTML

          <nav class="navBar">
            <div class="dropdown">
                <button class="dropbtn"  id="dropbutton">Style menu</button>
                <div class="dropdown-content">
                    <a href="#" class="bold">Bold</a>
                    <a href="#" class="italic">Italic</a>
                </div>
            </div>
            <div class="dropdown">
                <button class="dropbtn"  id="dropbutton1">Thèmes site</button>
                <div class="dropdown-content">
                    <a href="#" class="fonce">Fonce</a>
                    <a href="#" class="pale">Pale</a>
                </div>
            </div>
        </nav>


// JAVASCRIPT

const bold = document.querySelector(".bold");
const italic = document.querySelector(".italic");
const fonce = document.querySelector(".fonce");

function Mystyle(){
   bold.style.fontWeight = "bold";
   italic.style.fontWeight = "bold";
   fonce.style.fontWeight = "bold";
  
};

bold.addEventListener("click", Mystyle);


// It does not work
function removeEvent() {
    bold.removeEventListener("click", Mystyle);
  }

>Solution :

Do not remove the event listener; instead, change the styles (or toggle a class) depending on the current state for each click.

function Mystyle(){
    if (bold.style.fontWeight === 'bold')
        bold.style.fontWeight = italic.style.fontWeight = fonce.style.fontWeight = "";
    else
        bold.style.fontWeight = italic.style.fontWeight = fonce.style.fontWeight = "bold";
  
};
bold.addEventListener("click", Mystyle);

It is more convenient to toggle a class instead:

function Mystyle() {
  document.querySelector('.navBar').classList.toggle('bold');
}
document.querySelector('.bold').addEventListener("click", Mystyle);
.navBar.bold .bold, .navBar.bold .italic, .navBar.bold .fonce {
/* or perhaps use .navBar.bold a */
  font-weight: bold;
}
<nav class="navBar">
  <div class="dropdown">
    <button class="dropbtn" id="dropbutton">Style menu</button>
    <div class="dropdown-content">
      <a href="#" class="bold">Bold</a>
      <a href="#" class="italic">Italic</a>
    </div>
  </div>
  <div class="dropdown">
    <button class="dropbtn" id="dropbutton1">Thèmes site</button>
    <div class="dropdown-content">
      <a href="#" class="fonce">Fonce</a>
      <a href="#" class="pale">Pale</a>
    </div>
  </div>
</nav>

Leave a ReplyCancel reply