I know there are a lot of posts about this, but I can't find an answer to my specific problem.
I would like to make a JS variable the value of an HTML attribute:
<script> var screenWidth = screen.width </script>
<img src="images/title.png" width="VARIABLE HERE" style="margin-top: 3%"`
"VARIABLE HERE"
is where I would want the screenWidth
variable to go. What is the best of going about this?
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html. Save this answer.
you don't declare variable in html... you can only declare variables in css (kind of) or in javascript ^^ assuming you meant "in javascript": by using 'var', 'let', or 'const' keywords... The <var> tag is used to highlight the variables of computer programs.
Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.
HTML attributes are generally classified as required attributes, optional attributes, standard attributes, and event attributes: Usually the required and optional attributes modify specific HTML elements. While the standard attributes can be applied to most HTML elements.
This should work:
<script>var screenWidth = screen.width;</script>
...
<img src="images/title.png" onload="this.width=screenWidth;" style="margin-top: 3%">
Give the tag an id.
i.e. <img id="xxxx" ...>
Then use
document.getElementById('xxx').setAttribute('width', 'somevalue')
See setAttribute
Or use JQuery as the other poster noted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With