Reputation:
Why does this script not work?
<!DOCTYPE html>
<html>
<head>
<title>Hello StackOverflow!</title>
</head>
<body>
<div id="testing">
<p>Bladybla</p>
</div>
<script>
var one = window.innerWidth;
var two = 5;
var three = one / two;
var four = '"' + Math.round(three) + "px" + '"';
document.getElementById("testing").style.marginTop = four;
</script>
</body>
</html>
When I place an alert between var four
and the document.getElementById
is calculates the right value. The problem is in the .style.marginTop =
. It doesn't print the calculated value. WHY?
Thanks in advance, Jaapyse!
Upvotes: 3
Views: 5497
Reputation: 3353
write your script like :
<script>
var one = window.innerWidth;
var two = 5;
var three = one / two;
var four = Math.round(three);
document.getElementById("testing").style.marginTop = four + 'px';
</script>
Upvotes: 0
Reputation: 4671
When you set .style.marginTop, you don't need to include quotes in your value.
If you were setting it to a hardcoded value, you might have:
document.getElementById("testing").style.marginTop = "5px";
However, you're effectively setting it to something like:
document.getElementById("testing").style.marginTop = '"5px"';
This is then an invalid value, so it gets ignored.
Change your code to this:
var one = window.innerWidth;
var two = 5;
var three = one / two;
var four = Math.round(three) + 'px';
document.getElementById("testing").style.marginTop = four;
Upvotes: 5