I have a javascript variable that I want to include it in my html code. The code is like this:
<a href="index.html"><img src="Images/Icones/Mes_commandes.png" alt="France" id="im1">MY_JS_VARIABLE</a></li>
How can I do?
I have a javascript variable that I want to include it in my html code. The code is like this:
<a href="index.html"><img src="Images/Icones/Mes_commandes.png" alt="France" id="im1">MY_JS_VARIABLE</a></li>
How can I do?
If you use the after() function proposed in dldnh's solution, then it'll be hard to keep your code organized as you want javascript to do more on your page (you'll have to add everything in the after function since Javascript can only have one onload event handler).
If you plan to use more javascript on the page, a better option would be to use jQuery. Like so:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>$(function() {
$('#im1a').html(yourVariable);
});
</script>
</head>
<body>
<li><a href="index.html"><img src="Images/Icones/Mes_commandes.png" alt="France" id="im1"></a><a id="im1a" href="index.html"></a></li>
</body>
</html>
the timing can be a little tricky, because you either write the whole page using javascript or you make changes to it after it's written. here's what I would do. Write the HTML and after the content has loaded the after
function will change the tag as you indicated.
<html>
<head>
<script type="text/javascript">
function after()
{
var anchor = document.getElementById("im1a");
anchor.innerHTML = "Inserted Text";
}
</script>
</head>
<body onload="after()">
<li><a href="index.html"><img src="Images/Icones/Mes_commandes.png" alt="France" id="im1"></a><a id="im1a" href="index.html"></a></li>
</body>
</html>
The best way I have found is to just include that data in a hidden form element, and then my javascript can get it and use it. This way I can also have it behave in some appropriate fashion if javascript is turned off, by putting in a default value that will make sense.
My javascript code would replace that with the correct (for the given situation) value if javascript is enabled.
Here is a solution that builds a menu. This may be what you are looking for.
<ul id='country_menu'>
</ul>
<script>
var images = new Array();
images[0] = "Images/Icones/Mes_commandes.png";
images[1] = "Images/Icones/other.png";
images[2] = "Images/Icones/yetanother.png";
var captions = new Array();
captions[0] = "MY_JS_VARIABLE";
captions[1] = "other caption";
captions[2] = "yet another caption";
var options_html = "";
for (i = 0; i < images.length; i++)
{
options_html += "<li>";
options_html += "<a href='index.html'>";
options_html += "<img src='"+images[i]+"' alt='"+captions[i]+"' />";
options_html += captions[i];
options_html += "</li>";
}
document.getElementById('country_menu').innerHTML = options_html;
</script>