Home > Software engineering >  remove addEventListener for font-weight - Javascript
remove addEventListener for font-weight - Javascript

Time:01-31

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 >
            <div >
                <button   id="dropbutton">Style menu</button>
                <div >
                    <a href="#" >Bold</a>
                    <a href="#" >Italic</a>
                </div>
            </div>
            <div >
                <button   id="dropbutton1">Thèmes site</button>
                <div >
                    <a href="#" >Fonce</a>
                    <a href="#" >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);
  }

CodePudding user response:

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 >
  <div >
    <button  id="dropbutton">Style menu</button>
    <div >
      <a href="#" >Bold</a>
      <a href="#" >Italic</a>
    </div>
  </div>
  <div >
    <button  id="dropbutton1">Thèmes site</button>
    <div >
      <a href="#" >Fonce</a>
      <a href="#" >Pale</a>
    </div>
  </div>
</nav>

  • Related