I am facing an issue in my code where a random element is generated within the body and when clicked, it is replaced with another gif element. I am using offset() to obtain the top and left values of the original image, and then using replaceWith() to swap it with the gif. Additionally, I use css() to set the left and top values of the gif like this:
function randomInt(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
var thewidth = randomInt(1,1000);
$("body").prepend( "<img src='red_dot.png' class='enemies' id='enemy' left:thewidth/2 + 'px'></img>");
var n = $("#enemy").offset();
console.log(n.left);
console.log(n.top);
$("#enemy").click(function()
{
$("#enemy").replaceWith("<img src='explosion.gif' id = 'explosion'></img>");
$("#explosion").css({"left" : n.left+'px', "top" : n.top + "px"});
.enemies
{
position: fixed;
transform: scale(0.01,0.01);
}
#explosion
{
transform: scale(0.1,0.1);
position: fixed;
}
Although the top and left values are the same for both elements, they appear at different positions when the code is executed. I am unsure why this happens and how I can ensure that the gif always replaces the image at its exact position. Can anyone provide insights into this issue?