skip to Main Content

I am trying to get the "left" and "top" attributes to be set to the value gotten from "randomXValue" and "randomYValue" the two functions return integers.

randomXValue = getRandomXValue();
randomYValue = getRandomYValue();

$("#gamespace").append(
    '<img src="img/img.jpg" class="gameimg" style = "left: (randomXValue)px; top:
        (randomYValue)px;"/>'
);

if I put in an integer instead of the randomValue it will display in the correct location. I am trying to get the image to appear at a random location in the "#gamespace"

2

Answers


  1. It is important to note the order in which the quotes are placed.

    In your example, we start with single quotes, which are used to define the start and end of the string. To insert variables into the string, we can split the string by inserting a single quote at any point and concatenate the variable with the string using the plus sign.

    You have to insert the variable as follows

    randomXValue = getRandomXValue();
    randomYValue = getRandomYValue();
    
    $("#gamespace").append(
        '<img src="img/img.jpg" class="gameimg" style = "left: "'+randomXValue+'"px; top:"'+randomYValue+'"px;"/>'
    );
    
    Login or Signup to reply.
  2. Use template strings for readability

    const left = getRandomXValue();
    const top = getRandomYValue();
    $("#gamespace").append(
        `<img src="img/img.jpg" class="gameimg" style="left:${left}px;top:${top}px;"/>`
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search