Make slide inside a div

0

This script makes a slide inside the body.

My question is: How do I make the slide work inside a specific div?

var imageCount = 0;

var currentImage = 0;

var images = new Array();

images[0] = 'img/01.jpg';

images[1] = 'img/02.png';

images[2] = 'img/03.jpg';


var preLoadImages = new Array();

for (var i = 0; i < images.length; i++)
{
   if (images[i] == "")
   break;

   preLoadImages[i] = new Image();

   preLoadImages[i].src = images[i];

   imageCount++;
}

function startSlideShow()
{
   if (document.body && imageCount > 0)

   {
      document.body.style.backgroundImage = "url("+images[currentImage]+")";  

      document.body.style.backgroundAttachment = "fixed";

      document.body.style.backgroundRepeat = "no-repeat";

      document.body.style.backgroundPosition = "left top";

      document.body.style.backgroundSize = "100% 100%";

      currentImage = currentImage + 1;

      if (currentImage > (imageCount-1))
      { 
         currentImage = 0;
      }
      setTimeout('startSlideShow()', 5000);
   }
}
startSlideShow();
    
asked by anonymous 08.06.2017 / 18:44

1 answer

0

Assign an id to your div, in the example below I assign the id slide like this:

  

HTML

<div id="slide"></div>

Format the dimension of the div:

  

CSS

#slide { width: 300px; height: 300px; }

And change your JavaScript code to retrieve the div by its ID. In my test I needed to remove the line from the code slide.style.backgroundSize = "100% 100%";

  

JavaScript

var imageCount = 0;

var currentImage = 0;

var images = new Array();

images[0] = '1.png';

images[1] = '2.png';

images[2] = '3.png';

var slide = document.getElementById('slide');

var preLoadImages = new Array();

for (var i = 0; i < images.length; i++)
{
   if (images[i] == "")
   break;

   preLoadImages[i] = new Image();

   preLoadImages[i].src = images[i];

   imageCount++;
}

function startSlideShow()
{
   if (slide && imageCount > 0)

   {
      slide.style.backgroundImage = "url("+images[currentImage]+")";  

      slide.style.backgroundAttachment = "fixed";

      slide.style.backgroundRepeat = "no-repeat";

      slide.style.backgroundPosition = "left top";

      currentImage = currentImage + 1;

      if (currentImage > (imageCount-1))
      { 
         currentImage = 0;
      }
      setTimeout('startSlideShow()', 5000);
   }
}
startSlideShow();

Note: But you still have to solve the problem that the images should be of the same size as the size that is set in CSS.

    
08.06.2017 / 19:01