Slide inside a div

Asked

Viewed 331 times

0

This script makes a "slide" inside the body.

My question is: How do I get the slide to 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();

1 answer

1

Assign an id to your div, in the example below 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 had 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 the same size as the CSS define.

  • I had done the same procedure but it didn’t work , var slide = Document.getElementById("slide"); I think it was because of the double quotes , I put single quotes and it worked _, Thanks for your help !!

  • Then see how to vote and accept: https://answall.com/tour

Browser other questions tagged

You are not signed in. Login or sign up in order to post.