Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 635
benjipelletier Avatar asked Feb 08 '14 08:02

benjipelletier


People also ask

Can you use JS variables in HTML?

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.

Can you declare variables in HTML?

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.

How do you store variables in HTML?

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.

What are the 3 types of attribute in HTML?

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.


2 Answers

This should work:

<script>var screenWidth = screen.width;</script> 
...
<img src="images/title.png" onload="this.width=screenWidth;" style="margin-top: 3%">
like image 65
ElDoRado1239 Avatar answered Oct 23 '22 23:10

ElDoRado1239


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

like image 40
user3286701 Avatar answered Oct 23 '22 23:10

user3286701