Reputation: 3
How would I use a variable in this line? My variables are "rand1" and "rand2"
style="position:absolute; TOP:'rand1'px; LEFT:'rand2'px"
This is my full code.
<script>
var rand1 = Math.floor(Math.random() * 1000) + 1
var rand2 = Math.floor(Math.random() * 1000) + 1
</script>
<img id="myImage"
src="redsquare.jpg"
width="100"
height="100"
style="position:absolute; TOP:'rand1'px; LEFT:'rand2'px"
onClick="alert(rand1); alert(rand2)">
My intention for this code is for an image to pop up on screen at a random location, and it is clickable, but this code only puts the red square image at the top left corner.
In position:absolute, there would usually be a number where my variables are, and there would be no quotation marks, so it would look like this:
style="position:absolute; TOP:100px; LEFT:200px"
I thought I could just replace the numbers with a variable, but that did not work.
Upvotes: 0
Views: 64
Reputation: 21575
You could instead do a document.write()
in JavaScript for the <img>
:
<script>
var rand1 = Math.floor(Math.random() * 1000) + 1
var rand2 = Math.floor(Math.random() * 1000) + 1
document.write("<img ... style='position:absolute; TOP:"+rand1+"px"+" LEFT:"+rand2+"px' ...");
</script>
Or simply change the values of .top
and .left
via JavaScript. For example:
document.getElementById("myImage").style.top = rand1;
document.getElementById("myImage").style.left = rand2;
Upvotes: 0
Reputation: 388316
The script variables are not evaluated when parsing css values.
You can use script to change the style value
<img id="myImage" src="redsquare.jpg" width="100" height="100" style="position:absolute;" onClick="alert(rand1); alert(rand2)" />
<script>
myImage.style.top = Math.ceil(Math.random() * 1000) + 'px';
myImage.style.top = Math.ceil(Math.random() * 1000) + 'px';
</script>
Note that the script is placed after the element is created.
Upvotes: 1