Javascript variables in HTML attributes

You can add the style using javascript to particular element like this.

script

document.getElementById('myImg').style.width = screen.width + "px";

Html

<img id="myImg" src="images/title.png"  style="margin-top: 3%">

Here is a demo


You can't simply call a JavaScript variable inside your HTML. You'll need to have it written by JavaScript or JQuery. You can do it this way :-

 <input id="myInput" .../>
 <script>
    var myVar = "value";
    $("#myInput").attr("name", myVar);
 </script>

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


This should work:

<script>var screenWidth = screen.width;</script> 
...
<img src="images/title.png" onload="this.width=screenWidth;" style="margin-top: 3%">