jQuery make image popup in random position not working

Viewed 174

I want to make an image randomly show up every 2 sec using jQuery. But the image always shows in a static position (top-left). I console.logged the attribute of the image and its left and top shows random px.

let score = 0;
let id = 0;
$(document).ready(function () {
  setInterval(setImage, 2000);
});

function setImage() {
  $("#container").append(
    `<img src='images/virus.gif' id='${id}' width='75px' position='absolute' class='virus' left=${randomLeft()} top=${randomTop()}/>`
  );

  $("#" + id)
    .slideUp(0)
    .fadeIn(1000);

  id++;

  $("#" + id).on("click", function (event) {
    $(event.target).remove();
    score++;
    console.log($(event.target).attr("id"), score);
  });
}

function randomTop() {
  let height = $(window).height();
  let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
  return randomHeight;
}

function randomLeft() {
  let width = $(window).width();
  let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
  return randomLeft;
}

1 Answers

You need to use style rather than left/top attributes

style="left:10px;right:10px"

Couple of other tweaks to your snippet:

  • include jquery (option on the left of snippet editor adds <script> to the html)
  • needs a #container to put them in, I made this position:relative so the position:absolute will work
  • removed the need for the $("#"+id) re-finding by chaining the append
  • put the i++ at the beginning so that you don't try to attach click to something that doesn't exist yet (but doesn't matter as not used for re-finding new element)
  • $(this).remove() must come after $(this).attr("id") - you were removing it before getting its ID
  • used this inside the click handler rather than event.target
  • would be better as data-id=${++id} rather than using a numerical id, but that's a small change (not made)

Updated snippet:

let score = 0;
let id = 0;
$(document).ready(function() {
  setInterval(setImage, 2000);
});

function setImage() {
  var img = $(`<img src='images/img4.jpg' id='${++id}' class='virus' style='left:${randomLeft()};top:${randomTop()}' />`);

  img.appendTo("#container")
    .slideUp(0)
    .fadeIn(1000)
    .on("click", function() {
      score++;
      console.log($(this).attr("id"), score);
      $(this).remove();
    });
}

function randomTop() {
  let height = $(window).height();
  let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
  return randomHeight;
}

function randomLeft() {
  let width = $(window).width();
  let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
  return randomLeft;
}
#container {
  position: relative;
  height: 100%;
  width: 100%;
}

.virus {
  border: 1px solid red;
  position: absolute;
  width: 75px;
  height: 20px;
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>

Related