0

I feel as though this should work. I'm creating a variable in javascript and referencing it in the same file. Can someone explain why this is not working and then show how I can achieve my intended result? I feel as though I'm missing something obvious.

*edit: I forgot to mention that it is important that I use a javascript variable as my color. Sorry.

<!DOCTYPE html>
<html>

<head>
</head>

<body style="background-color:color;">
</body>
<script type="text/javascript">
	var color = #555555;
</script>

</html>

6
  • That just does not work. Browsers don't work that way. Commented Jan 18, 2018 at 16:10
  • HTML doesn't parse JS variables, you'd have to do it all through JS Commented Jan 18, 2018 at 16:10
  • Is there anything I can do to use a javascript variable as a color? Commented Jan 18, 2018 at 16:13
  • See my answer below Commented Jan 18, 2018 at 16:13
  • @AndyHolmes You're the best! Thanks Commented Jan 18, 2018 at 16:15

2 Answers 2

1

Your example of use isn't how browsers work. If you wanted to achieve your example properly you could try

<script type="text/javascript">
    var color = '#555555'
    document.body.style.backgroundColor = color;
</script>

https://jsfiddle.net/8dgoddw8/ - shows it working

Sign up to request clarification or add additional context in comments.

Comments

0

You can instead use this on your javascript:

  var color = '#555555';
  document.body.style.backgroundColor = color;

2 Comments

@JeremyThille "It's the exact same answer as the other one" might have been a giveaway.
Uuuuuuh... And except <script type="text/javascript">, what's different? Anyway, silent downvotes are always a pain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.