Reputation: 31
I want to use a variable sym
to change how a script loads on the page. I can load the script if I hard code the src URL, but I can't use JavaScript to build the URL within the src
attribute of the script tag.
<script>
var sym = "MSFT";
document.write(sym);
</script>
<script src="http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=$SPX+MSFT&Output=JS"></script>
<!-- works -->
<script src="http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=$SPX+"+sym+"&Output=JS"></script>
<!--- does NOT work because I do not know how to insert the var correctly -->
Upvotes: 1
Views: 5483
Reputation: 434
How do you pass a variable as a part of an URL?
Easy! Since you don't mind using javascript a simple solution is as follows
var scriptElement = document.createElement("script");
scriptElement.src = "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS";
document.head.appendChild(scriptElement);
This code creates an script element with the source being "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS". Then it appends it to the head of the webpage.
The final HTML being:
<script>
var sym = "MSFT";
document.write("\<script src='" + "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS" + "'\>\</script\>");
</script>
The reason that this solution won't work is as follows:
Codepen is an HTTPS site which means it WILL NOT serve HTTP content. To be honest I have no idea why Codepen serves the HTTP script. How to fix this? Well, there really is only one easy solution:
Instead of using Codepen use a local HTML file and just open that, if you have your own HTTP server you can use that.
Quick how-to guide:
1) Open a text editor
2) Type the following
<html>
<head>
<script>
var sym = "MSFT";
document.write("\<script src='" + "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS" + "'\>\</script\>");
</script>
</head>
<body>
</body>
</html>
3) Now hit the "Save As" button and save it as a .html file
4) Open it!
5) Have fun :)
Upvotes: 2
Reputation: 370729
You can't use Javascript variables inside of HTML markup like that - you'll have to create the script tag yourself fully in Javascript alone. For example:
<script>
var sym = "MSFT";
document.addEventListener('DOMContentLoaded', () => {
document.head.appendChild(document.createElement('script'))
.src = `http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=$SPX${sym}&Output=JS`;
});
</script>
Upvotes: 0