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?
Give the tag an id.
<img id="xxxx" ...>
Or use JQuery as the other poster noted
document.getElementById('myImg').style.width = screen.width + "px";
<img id="myImg" src="images/title.png" style="margin-top: 3%">
Here is a demo
<input id="myInput" .../> <script> var myVar = "value"; $("#myInput").attr("name", myVar); </script>
This should work:
<script>var screenWidth = screen.width;</script> ... <img src="images/title.png" onload="this.width=screenWidth;" style="margin-top: 3%">
In this case, you could set the width to either
100vw using CSS (possibly via the style attribute:
style="width: 100vw;". This is more efficient and more readable, but isn't supported in some old browsers.
©2020 All rights reserved.