benjipelletier
benjipelletier

Reputation: 663

Javascript variables in HTML attributes

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?

Upvotes: 19

Views: 93553

Answers (5)

Solomon Ucko
Solomon Ucko

Reputation: 6109

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.

Upvotes: 0

Suman Bogati
Suman Bogati

Reputation: 6349

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

Upvotes: 4

user3286701
user3286701

Reputation: 8621

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

Upvotes: 5

Vivek Sadh
Vivek Sadh

Reputation: 4268

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>

Upvotes: 1

ElDoRado1239
ElDoRado1239

Reputation: 4048

This should work:

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

Upvotes: 18

Related Questions