Using Variables in HTML Markup - JavaScript

Hi All,

Is there a way to use a JavaScript Variable inside of a HTML file? Do I need to use another library? Basically, I want to make it easy for for someone who doesn’t know HTML to edit all the urls in one place.

(screenshot of code below)

Thanks in Advance!

If you put variables in a <script> tag, they can be right there in the HTML. Those variables will be global and will be accessible from any other JavaScript running in the page. This will let you have variables that can be easily exposed and editable from anyone with access to edit the HTML without them having to dig through other code).

1 Like

Thank you. Here’s is what I’m trying to do. Somehow it wasn’t included in my original post.

Ah, yeah that’s a little different. HTML itself doesn’t support anything like this. Usually that’s handled by some other framework or templating engine.

You could create a script a the end of your HTML to go through and make the replacements after the HTML is parsed. But you have to be careful with things like src attributes because the browser will throw a lot of errors with bad requests when it tries to load the url “{{imgSrc1}}” and can’t find it.

To get around this you could put the properties in a data attribute and then have your script move them to the original when making the replacements

<script>
var imgSrc1 = "https://placehold.co/300x300";
var imgSrc2 = "https://placehold.co/200x200";
var imgSrc3 = "https://placehold.co/100x100";
</script>

<img data-src="imgSrc1" />
<img data-src="imgSrc2" />
<img data-src="imgSrc3" />

<script>
// make replacements for data attributes
for (let img of document.querySelectorAll('img[data-src]')) {
	img.src = window[img.dataset.src]
}
</script>

This is a very simple implementation that specifically targets images with a src property. You may need to get more involved depending on where and how you want to use variables like this.

1 Like

Senocular’s advice is the advice you should take, but I couldn’t resist:

<!doctype html>
<html>
  <head>
    <meta charset=utf-8">
    <script type="text/javascript">
    let imageSource1 = 'image1.jpg'
    let imageSource2 = 'image2.jpg'
    let imageSource3 = 'image3.jpg'
    let imageSource4 = 'image4.jpg'
    let imageSource5 = 'image5.jpg'

    let _ = (_, src, self) => {
      self.setAttribute('src', src)
      self.setAttribute('onerror', '')
    }
    </script>
  </head>
  <body>
    <div>
      <img src onerror="_`${imageSource1} ${this}`" />
      <img src onerror="_`${imageSource2} ${this}`" />
      <img src onerror="_`${imageSource3} ${this}`" />
      <img src onerror="_`${imageSource4} ${this}`" />
      <img src onerror="_`${imageSource5} ${this}`" />
    </div>
  </body>
</html>

Edit: Improved to match my original vision a bit more. Quite close to {{ imageName }}!!

1 Like

Thank you for the help! I ended up doing it a little differently but it works:

One thing to keep in mind about document.write is that it will clear out everything in your page. The approaches sen and kril outlined above will allow you to keep your page content while also having images whose paths are defined in HTML :robot:

1 Like

It will do this only if called after the page is finished parsing. In georgetown23’s example, it will work as expected, retaining the rest of the page’s contents.

That said, for this reason, and others, generally you’ll want to steer clear of document.write.

2 Likes

Hello All! I did a bit more research and believe using Template Literals is a better/modern way to do it? (BTW- how do we add actual code here?)

If you’re talking about JavaScript code, then yes. Template literals allow you to add substitutions directly in JavaScript string literals when using back ticks (`). But now you’re writing HTML in JavaScript which can get confusing.

Given:

it sounded like you wanted to keep things simple for people who don’t know HTML very well. And if they wanted to edit an <img> tag, having that inside the JavaScript code could make that difficult.

Now if this “someone” is only interested in the variables and nothing else, then it doesn’t really matter. You can take any number of approaches to convert the variables into image paths. I think that’s up to you and whatever you feel comfortable with.

I, personally, like keeping everything together to help prevent surprises. For example, upon seeing

<div id="content"></div>

I’m immediately going to think, “Oh nice, an empty div. How uninteresting!” Little do I know that div is going to get populated with image elements after some script later down the road eventually runs.

With my previous example there’s image tags where there’s going to be image tags, and with a little guessing you can probably equate data-src attributes to src attributes thanks to a little hidden magic somewhere, but at least you know the images are there.

Once you add code, you can select it and click on the code icon in the editor: image

You can also format code manually by using a single back tick for inline code `such as this`. Or for block code indenting by 4 spaces

    such
    as
    this

For block code, you can also use 3 back ticks along with an optional language to help with color coding. If you don’t specify a language one will be inferred.

```
like
this
```

or

```javascript
like
this
```

The code icon will default to 4 spaces for multiline code, but if you want more control over formatting you might want to force it with 3 back ticks.

… and yes, having the code as text in posts is better than screenshots :wink:

Thank you for the detailed response! Makes sense that they shouldn’t have too look elsewhere for the code. I’ll keep optimizing but I’m all set here. :grinning:

1 Like

Hi George,
The easiest way to achieve that is to set the url in a css variable on the object
eg. <div id = ‘one’ class = ‘image’ style = '- -imgSrc: '‘www.eg one";’ >.<div id = ‘two’ class = ‘image’ style = '- -imgSrc: '‘www.eg two";’ >.
Then set the background image as the url in your CSS.
e.g. .image{ background-image: var(- -imgSrc);}
The CSS will then block scope the variable to the element because it is inline and display the correct image for each div despite having the exact same variable name.
This is super handy for complex animations because you can change a class on a parent element and the children update with their different variables, you can also run a single animation and have different effects on different elements.
(I have only used this for animations but I seen no reason why it wouldn’t work for urls)
Good luck,
P.S- misunderstood what you where trying to do (I’m fragged, disregard :grin:)

1 Like