Home > Blockchain >  Controlling Multiple Elements from a Single Event Listener
Controlling Multiple Elements from a Single Event Listener

Time:06-07

I am trying to toggle classes on 2 elements from a single event listener, but only the first element gets modified.

const toggleBtn = document.querySelector(".toggle-btn");
const slideoutSidebar = document.querySelector(".slideout-sidebar");

const slideTheBar = function () {
  toggleBtn.classList.toggle("toggle-slide");
  slideoutSidebar.classList.toggle("slideout-slide");
};

toggleBtn.addEventListener("click", slideTheBar);

I have these two elements (toggleBtn, slideoutSidebar) and I have created a function that toggles a class for each element. I then attach this function to an event listener for the toggleBtn element.

The problem is that when the event is executed, only the first line of code of the function is working toggleBtn.classList.toggle("toggle-slide");

While the second slideoutSidebar.classList.toggle("slideout-slide"); is not. What am I doing wrong?

CodePudding user response:

This seems to be working fine?

const toggleBtn = document.querySelector(".toggle-btn");
const slideoutSidebar = document.querySelector(".slideout-sidebar");
console.log(toggleBtn);

const slideTheBar = function () {
  toggleBtn.classList.toggle("toggle-slide");
  slideoutSidebar.classList.toggle("slideout-slide");
};

toggleBtn.addEventListener("click", slideTheBar);
.slideout-sidebar {
  display: block;
  height: 200px;
  width: 100px;
  position: absolute;
  top: 0;
  right: -200px;
  background: #F05D7C;
  color: #fff;
  font-size: 20px;
  transition: all 0.3s ease-in;
}
.slideout-slide.slideout-slide {

  right: 0
}
<button >Toggle</button>
<div >Slide me in</div>

  • Related