Search code examples
javascripthtmlwebfrontendvs-web-site-project

How to create a series of images with Javascript to form loading screen under another image?


I'm having a tough time trying to generate 10 little squares (every 1 second) in a row that would simulate pixels in a loading bar, while having them appear just under another image of a rabbit. Right now it's working but they appear forming a vertical line instead of a row.

This is the javascript code:

var rabbit = document.getElementById("rabbit");

  for(var i=0; i < 10; i++){
   setTimeout(() => {
   var pixel = document.createElement('img');
   pixel.setAttribute('src', 'static/images/test/pixel.png');
   pixel.setAttribute('height', '10px');
   pixel.style.marginLeft = "10px";
   document.body.appendChild(pixel);
  rabbit.after(pixel);
}, i*1000+1500);
}

And this is the HTML tag of the rabbit image:

   <img id='rabbit' src='{% static 'images/cartelera_home/ghost.gif' %}' alt='' style='height:0px'>

I don't think it is relevant, but I'm using Django to build this website and bootstrap, and so far there's no CSS code in this page.

Just any kind of help will be highly appreciated.


Solution

  • I'm having a tough time trying to generate 10 little squares (every 1 second) in a row that would simulate pixels in a loading bar, while having them appear just under another image of a rabbit. Right now it's working but they appear forming a vertical line instead of a row.

    This seems to be working as you expect unless I am mis-understanding. it looks like a progress bar - I just substituted your code with a blue box using a data uri.

    You can see it here https://codesandbox.io/s/peaceful-wilbur-d2tuf?file=/index.html'

    Is it possible you have other code/styles interfering with the outcome?