0

I'm trying to including a css "left" property to my javascript code such that if the left property in the css file matches the one in the javascript code, a certain action takes place. Any help will be appreciated. The HTML code is:

<!DOCTYPE HTML>
<html>
<head></head>
<body>

<button id = "myBtn">MyButton<button>

<p id= "demo"></p>

</body>
</html>

The CSS code is:

#myBtn {
   position: absolute;
   left: 100px;
}

The script code is:

<script>
if (document.getElementById("myBtn").style.left == "100px") {
   actionX //this is just an example
   }
document.getElementById("demo").innerHTML = actionX;
</script>
coder_1
  • 1
  • 2
  • 1
    = is assignment, == tests for equality, === really tests for equality – Jaromanda X Jul 09 '15 at 02:45
  • 1
    Whoops, wrong duplicate. Here's a better match: http://stackoverflow.com/questions/4866229/can-you-check-an-objects-css-display-with-javascript or http://stackoverflow.com/questions/13778439/how-to-get-the-css-left-property-value-of-a-div-using-javascript – cimmanon Jul 09 '15 at 02:53

1 Answers1

0

Well you're setting the property value with the = operator, you want to use the == operator. In some rare unusual cases which I can't seem to think of, you'd do an assignment in an if statement, but setting a property of an object will return a truthy value in JS, so the branch will always be reached.

if (document.getElementById("demo").style.left == "100px") {
    actionX (just an example) 
}
Ryan
  • 14,392
  • 8
  • 62
  • 102