2

I'm trying to make an image fall, similar to a rain effect, but I only want it triggered by an event listener.

Currently, I'm appending a div and animating the falling effect, but each additional event trigger is then appended below/next to the first.

function appendImage() {
  var img = document.createElement('img');
  img.setAttribute('src', 'http://pixelartmaker.com/art/3ba7f5717ac3c63.png');
  $('#action').append(img);
}
@keyframes slidedown {
  0% {
    margin-top: 0%;
  }
  100% {
    margin-top: 150%;
  }
}

img {
  animation-duration: 20s;
  animation-name: slidedown;
  height: 100px;
  width: 100px;
}
<input type="button" value="Test Button" onclick="appendImage();" />
<div id="action"></div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

I'm trying to get the image to spawn from a random place on the x axis but always from the top of the screen.

codepen here.

kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • I'm not sure if it fully answers your question, but there is some good info about making a div appear at random locations within window limits here -- https://stackoverflow.com/questions/4796743/random-position-of-divs-in-javascript – Christopher Bennett May 05 '19 at 03:09

1 Answers1

1

You can used fixed position here so that the elements can be independently moved across the viewport - now you can use top value for your animation and left to randomly spread it horizontally.

Also note the usage of animation-fill-mode: forwards which ensures that after animation the image do not come back to the top of the window.

See demo below and updated codepen here:

var rainDiv = document.querySelector('#action');
function appendImage() {
  var img = document.createElement('img');
  img.setAttribute('src', 'http://pixelartmaker.com/art/3ba7f5717ac3c63.png');
  img.style.left = Math.floor(Math.random() * 100) + 'vw';
  rainDiv.appendChild(img);
}
img {
  position: fixed;
  animation-duration: 20s;
  animation-name: slidedown;
  animation-fill-mode: forwards;
  height: 100px;
  width: 100px;
  top: 0;
}

@keyframes slidedown {
  to {
    top: 120%;
  }
}
<input type="button" value="Test Button" onclick="appendImage();" />
<div id="action"></div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95