1

I am doing some experiments and i have this code now, i have a class that is added dynamically to all of my 3 containers whenever the button clicked.

The class is added successfully to all divs but only one div that is animated!!

const hamburgers = [...document.getElementsByClassName('hamburger')];
const btn = document.getElementById('btn');


btn.addEventListener('click', () => {
    hamburgers.forEach(hamburger => {
        if(!hamburger.classList.contains('move'))  hamburger.classList.add('move') ;
        else hamburger.classList.remove('move')
    })
})
.hamburger {
    position: relative;
}

.bar {
    background: orange;
    position: absolute;
    width: 50px;
    height:5px;
    margin-top: 20px;
}

.bar:nth-of-type(1) {
    top:50px;
}

.bar:nth-of-type(2) {
    top: 100px;
}

 .bar:nth-of-type(3) {
    top: 150px;
} 

#hamburger-1 {
    left: 500px;
    background: #eee;
}

#hamburger-3 {
    left: 700px;
} 

.move {
    left: -150%;
    transition: left 0.4s ease-in-out;
}
<div class="hamburger" id="hamburger-1">
      <div class="bar"></div>
      <div class="bar"></div>
      <div class="bar"></div>
  </div>

  <div class="hamburger" id="hamburger-2">
      <div class="bar"></div>
      <div class="bar"></div>
      <div class="bar"></div>
  </div>

  <div  class="hamburger" id="hamburger-3">
      <div class="bar"></div>
      <div class="bar"></div>
      <div class="bar"></div>
  </div>
  <button id="btn">click</button>

Why left:-150% only work for one div and not the others when click the button??

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Saher Elgendy
  • 1,519
  • 4
  • 16
  • 27
  • ok, the issue is specificity .. ID will always win .. and only one element (the second) don't have an ID in the CSS file, so this one work fine – Temani Afif Feb 25 '19 at 14:35
  • The three divs are the same class, id, even children, one works and other not, and if it works for one it should work for all – Saher Elgendy Feb 25 '19 at 14:37
  • 1
    check your CSS code, you are adding left to only 2 element using ID selector, those one aren't working because ID is more specific than class. So they are different for the working one – Temani Afif Feb 25 '19 at 14:37
  • Your .move class is to weak. You can add the IDs like this [link](https://jsfiddle.net/51rjsdct/) – tom Feb 25 '19 at 14:38
  • i know about css specifity but this one tricked my mind, thank you you can add your answer so i can accept it. – Saher Elgendy Feb 25 '19 at 14:40

0 Answers0