Artur Grigio
Artur Grigio

Reputation: 5553

Using JS how to change HTML tag attributes (alternative to document.write() )

I am using an outside API that allows me to send extra parameters inside the image src value, like so

<img src="myImage.jpg?resize=width[scrW]">

The problem is that I don't know what the width variable(scrW) is until I start loading the page. I use <script> var scrW = window.innerHtml </script> to get the width I need.

I tried using

<script> 
    document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">')
</script>

but the problem with that is that document.write displays everything in text until the document is ready (or reaches </body>). And that just looks tacky.

My question is: How can I append/prepend JS variables to src attribut values during the page rendering?

Upvotes: 1

Views: 96

Answers (2)

M. Awwab Tahir
M. Awwab Tahir

Reputation: 11

How about you give your image src some default resize value and when the page is loaded it will be updated. I have given the img an id of "myImage" so that I can access that in JavaScript code.

Here is the HTML:

<img id="myImage" src="myImage.jpg?resize=width[180]">

Insert this JavaScript at the end:

<script>var scrW = window.innerHTML;
document.getElementById("myImage").src = "myImage.jpg?resize=width["+scrW+"]";</script>

Upvotes: 1

Matthew Herbst
Matthew Herbst

Reputation: 31963

How about just solving the problem of the text showing up before the page renders? That's easy. Just make sure your code doesn't run until the page's HTML is completely loaded.

Vanilla JS solution:

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here
   document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">');
})();
</script>

Using jQuery:

<script>
$(document).ready(function() {
  document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">');
});
</script>

Upvotes: 1

Related Questions