javascript - Why is putting style inside if statement not working? -
i'm trying basic toggle clicking js... 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 , seems method uses toggle clicking pure js have no idea why it's not working me, ideas?
@dekel's answer explains wrong code. however, should work classes instead. not way faster retrieving window.getcomputedstyle
, it's 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>
wiki
Comments
Post a Comment