Home > Net >  How to remove classname using multiple classname in JavaScript
How to remove classname using multiple classname in JavaScript

Time:12-15

I just trying to manipulate the class name using offsetTop and ScrollY. I have multiple div with class name of flex. I just tying to add and remove the "slide" classname using conditional statement. I can add the "slide" classname while reaching offset boundary. But I can't remove the classname after exit the boundary. Please help me for this situation. I have attached the code below.

function GetScroll() {
  let FlexPositions = document.querySelectorAll(".flex");
  let RemoveClass = document.querySelector("div");
  FlexPositions.forEach(function(item) {
    if (item.offsetTop < window.scrollY   300) {
      RemoveClass.classList.remove('slide')
      item.classList.add('slide');
    }
  })

}
html,
body {
  min-height: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
}

.flex {
  display: flex;
  height: 100%;
}
<body onscroll="GetScroll()">
  <div >A</div>
  <div >B</div>
  <div >C</div>
  <div >D</div>
  <div >E</div>
  <div >F</div>
  <div >G</div>
</body>

CodePudding user response:

Here is working code

You need to get the element with the slide class

window.addEventListener("load", () => {
  let flexPositions = document.querySelectorAll(".flex");
  document.addEventListener("scroll", function() {
    flexPositions.forEach(item => {
      if (item.offsetTop < window.scrollY   300) {
        document.querySelector("div.slide").classList.remove('slide')
        item.classList.add('slide');
      }
    })
  })
})
html,
body {
  min-height: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
}

.flex {
  display: flex;
  height: 100%;
}

.slide {
  background-color: red
}
<div >A</div>
<div >B</div>
<div >C</div>
<div >D</div>
<div >E</div>
<div >F</div>
<div >G</div>

  • Related