Magdi Gamal
Magdi Gamal

Reputation: 678

Why is putting style inside if statement not working?

I'm trying to do a basic toggle clicking with js... I have this

 <div id="box"></div>
 <button id="btn"></button>

 #box {
   background: black;
   width: 50px;
   height: 50px;
   position: absolute;
   left: 50px;
 }

js:

var btn = document.getElementById('btn');
var box = document.getElementById('box');

btn.addEventListener('click', function(){

   if (box.style.left === '50px') {
     box.style.left = '200px'; 
   }

   if (box.style.left === '200px') {
     box.style.left = '50px'; 
   }

});

I looked it up and this seems to be the method everyone uses for toggle clicking with pure js so I have no idea why it's not working for me, any ideas?

Upvotes: 0

Views: 91

Answers (3)

baao
baao

Reputation: 73241

@Dekel's answer already explains what was wrong with your code. However, you should work with classes instead. Not only is this way faster than retrieving window.getComputedStyle, it's also much easier

var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  var box = document.getElementById('box');
  box.classList.toggle('left-50');
  box.classList.toggle('left-200');
});
.left-50 {
  left: 50px;
}

.left-200 {
  left: 200px;
}

#box {
  background: black;
  width: 50px;
  height: 50px;
  position: absolute;
}
<div id="box" class="left-50"></div>
<button id="btn">bt</button>

Upvotes: 1

M. Waheed
M. Waheed

Reputation: 907

Better use offset. Beside you are making a kind of toggle operation in here. Meanwhile, I modified your script to make it work:

 <div id="box"></div>
 <input type="button" id="btn" value=" Try it "> 
<style>
 #box {
   background: black;
   width: 50px;
   height: 50px;
   position: absolute;
   left: 50px;
 }

</style> 

<script>
var btn = document.getElementById('btn');
var box = document.getElementById('box');

btn.addEventListener('click', function(){


   if (box.offsetLeft == 50 ) {
        box.style.left = 200  ; 

   }
   else if (box.offsetLeft == 200 ) {
        box.style.left = 50; 

   }


});
</script>

Upvotes: 0

Dekel
Dekel

Reputation: 62556

  1. You should use the window.getComputedStyle instead (This way you will get the actual value of the style that applied to that element, and not just what's on the style attribute)..
  2. You are missing an else there (otherwise you will always get the two if and nothing will change)

var btn = document.getElementById('btn');
var box = document.getElementById('box');

btn.addEventListener('click', function(){
   if (window.getComputedStyle(box).left === '50px') {
     box.style.left = '200px'; 
   } else if (window.getComputedStyle(box).left === '200px') {
     box.style.left = '50px'; 
   }

});
#box {
   background: black;
   width: 50px;
   height: 50px;
   position: absolute;
   left: 50px;
 }
<div id="box"></div>
 <button id="btn"></button>

Upvotes: 2

Related Questions