How to create image slideshow using JavaScript

How to create image slideshow using JavaScript



this is part 35 of JavaScript tutorial in this video we'll discuss how to create a simple image slideshow using javascript will be using set interval and clear interval methods to achieve this we discuss these methods in detail in part 34 of this video series so here is what we want to achieve when we click this start slideshow button this slideshow should start and when we click stop slideshow this slideshow should stop so let's see how to achieve this let's flip to Egypt studio here I have an empty asp.net web application project to this project let's add a new folder let's name it images so this folder is going to contain the images for our slideshow I have Windows 7 operating system on my machine so when I navigate to this folder that is see users public pictures sample pictures folder here I've got the Vandal sample pictures what I have done is copied these pictures into another folder and change their names from 1 to 8 now let's copy these images and paste them within this images folder so now we have got the images required for our slideshow the next step is to design the user interface like this so for this we need one image element and two button elements so let's first create the image element let's set the source attribute to this first image so forward slash images 4/1 dot jpg and let's give it an ID let's call it image and let's also set height in width let's set height to 150 pixels and width also 250 pixels let's include an HTML break and then a button input type equals button and let's set the value to start slideshow we need another button let's change the value to stop slideshow so this moment when we run this within the image element we should have the first image displayed and then we have the stop and stop slideshow buttons right so when we click start slideshow we should be you know starting the slideshow that means we should be changing the source attribute of the image element dynamically so it should cycle all the images from 1 to 8 and then again it should start from 1 to 8 and then it should be in a loop when we click stop slideshow that's when it should stop the slideshow so let's see how to achieve this so I'm going to write a function here I'm going to call this change image so this is the function which is going to change dynamically the image that is displayed within the image element so to change the image that is displayed we need to change the source attribute so first we need to get the current image that is being displayed so at the moment we have the first image that is one dot jpg so we need to get that image number so first let's read the source attribute of this image element so let's create a variable let's call this image source equals document dot get bar and get element by ID and to this function we give the ID of this image element so from this image element what do we want we want to get an attribute value so which attribute value we want we want the source attribute value so get attribute and then specify the name of the attribute the name of the attribute is source so now this image source is going to contain this entire string from this string now we should get just this image number whether it is one two or three whatever is the image number so in order to get that number we can use this substring function in JavaScript so let's create another variable here let's call this current image number now from this variable we want to get this substring and substring method has got two parameters that is the position at which we want to start the extraction and the position way we want to end the extraction so we want to extract the substring from this position right so how do we get that position now the image name is present immediately after the last forward slash now it's very easy to get the index of this element all we need to do is use last index of method so image source dot last index off so this is going to return as the index of this slash the position of this forward slash now that's not where we want to start the extraction we want to start the extraction one character after that so after we get the index position of the last forward slash add one to it so that is going to be our start position where we want to start the extraction and the end position is going to be in our two positions after this forward slash okay that means we want to end extraction at this position so the end position character will not be included in the substring so now let's copy the same thing and specify two there okay so what is this going to do this is going to return us number one that is currently displayed and just to be sure that's what is being this No retrieved let's actually use a div element here let's put an HTML break and let's include a div element let's give it an ID of result and yeah document dot get element by ID that is the stiv tag dot inner HTML equals let's set the current image number so when we run this hand and we call this function let's call this function change image so it should display number one within that div tag just to make sure we're getting just the image number so now we've got the image number that is the current image number now what we want to do is change the source to the second image so in order to do that so let's get the image element and for this image element we want to set a new value for this source attribute so I'm going to use set attribute function and which attribute do we want to set the source attribute and now we want to set the source attribute so that's the attribute for which we want to set the value and the second parameter is the actual value so the value is going to be the same thing that is forward slash images so we can hard code that because that's not going to change forward slash now to this string we want to increment current image number by one so at the moment image 1 is being displayed the next image is in our current image number plus 1 so I'm going to put that in parentheses current image number plus 1 so what is this going to do it's going to add 1 to the current image so 1 plus 1 is going to be 2 so 4 slash images forward slash 2 and then we should also give the extension that is dot jpg so let's provide that extension dot jpg so that entire expression is going to you know set the image source that's going to be the value for this source attribute so now let's run this function and then when we click you know look at that for some reason it's not displaying the image okay why is that let's actually move this code to this line right here okay and let's actually call this function on this button click that is you know the first button click start slideshow so on click equals change image so when we run this first it should display image 1 and then when we click start slideshow it should display the second image look at that for some reason it's not displaying the second image let's see ways that you know to understand why it's not displaying the second image let's move this line right here so it's going to show us the current image number actually let's take this entire expression right here because that's what has got the problem you know if it is forming this value for the source attribute that is four slash images 4/2 dot jpg then it should have displayed the second image but that's not what we are getting you know it's not showing any image here then this function is called so something is going wrong so let's see what is that actually let's create another variable here let's call this new image equals and how are we forming that new image using this expression right here so I'm going to take this entire expression out of here and then store it in this variable and then I'm going to set I mean I am going to pass that variable to this function and I'm going to set it also as the value for this div innerhtml okay so now let's run this so it's displaying the first image now when I click start slideshow look at that you know look at the part that's where we have the problem we don't have an image with name 11 dot jpg so why are we getting 11 dot jpg that's basically because here you know when we are performing the addition it's actually concatenating them together instead of adding them so to solve this problem let's use number function so when we use number function and then when we pass this current image number to that it's going to convert that to a number and then add 1 to it so now it should add them instead of concatenative and I click start slideshow notice that now we get image to dot jpg okay so our function is working as expected for now let's comment what we have you know the code that is setting the innerhtml of the live – so here we have our change image function which is going to change the image dynamically within this image control now when I click start slideshow it should continually call this change image function and in order for us to do that we can make use of set interval function we discussed this function in detail in part 34 of this video series so I'm going to first create a global variable here I'm going to call this interval ID and then I'm going to create another function here let's call this start slideshow and this function is simply going to call set interval function and remember this function expects two parameters the function that we want to call the function that we want to call is change image and we want to call this every 500 milliseconds that is every half a second okay and then we know that this set interval method is going to return the identifier of the repeated action and we want to store that identifier in this interval ID variable because we need that if we want to cancel the repeated action so now I'm going to create another function stop slideshow and what I want to do here is call clear interval function and to this we are going to pass this interval ID which will cancel this slideshow so unclick off the start slideshow button we want to call this function start slideshow and then and unclick off stop slideshow button we want to call stop slideshow function all right so now let's go ahead and run this so we have the first image there let's click start slideshow so every half a second look at that it is changing the images as expected Oh something is going wrong okay for some time it is showing no image there let's see ways that now in order to understand that I'm going to uncomment this line because that's going to display the new image value so let's run this let's click start slideshow so two three four five six seven eight nine ten so we don't have it's going to nine and ten okay so we don't have nine and ten images after eight we want to go back to one okay so how are we going to do that now when we get the current image number if current image number is equal to eight then we want to start at one again so I'm going to change this to actually zero so when we change it to zero this expression right here is going to increment it by 1 so it will again start from one dot jpg so now we should not have that problem so let's click start slideshow so three four five six seven eight and then it goes back to one okay so now it's in loop now when we click stop slideshow the slideshow should stop and we click the start slideshow again the slideshow should start now if you want to increase or decrease the time at which the images are being changed all you need to do is change this delay here if you want the image to be changed every one second change it to 1000 milliseconds if you want even longer increase it to you know a bigger number now we can get rid of the development because we just included that for you know troubleshooting and we can also get rid of this code right here and we can move this expression directly into this function instead of that variable and we can get rid of that variable so the function has got just in our own six lines of code so pretty straightforward function here and then we are making use of start set into well and clear interval methods to start and stop slide show thank you for listening and have a great day

23 thoughts on “How to create image slideshow using JavaScript

  • May 21, 2019 at 5:26 pm
    Permalink

    My code will work onomuseover and onmouseout directly on image no button needed thanks 'kudvenkat'
    to share knowledge πŸ™‚
    <!–

    file structure…

    root folder

    index.php

    1.png

    images/

    –>

    <!– index.php–>

    <!– image src to display any rendom image –>

    <img id="image" src="1.png" style="width: 150px; height: 150px" onmouseover='startImageSlideShow()' onmouseout='stopImageSlideShow()' />

    <!– php code to count all jpg image files from a folder –>

    <?php

    $count = count(glob("images/*.jpg"));

    ?>

    <script type="text/javascript">

    var intervalId;

    function startImageSlideShow()

    {

    //thumbnails folder to run all photos in folder

    var imageSrc = document.getElementById('image').setAttribute('src' , 'images/1.jpg' );

    intervalId = setInterval(setImage, 500);

    }

    function stopImageSlideShow()

    {

    clearInterval(intervalId);

    //image src to display back rendom image

    var imageSrc = document.getElementById("image").setAttribute("src", "1.png");

    }

    function setImage()

    {

    var imageSrc = document.getElementById("image").getAttribute("src");

    var currentImageNumber = imageSrc.substring(imageSrc.lastIndexOf("/") + 1, imageSrc.lastIndexOf(".") );

    //var currentImageNumber = imageSrc.substring(imageSrc.lastIndexOf("/") + 1, imageSrc.lastIndexOf("/") + 2);

    if (currentImageNumber == <?php echo $count ; ?> ) { currentImageNumber = 0; }

    document.getElementById("image").setAttribute("src", "Images/" + (Number(currentImageNumber) + 1) + ".jpg");

    }

    </script>

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    Good class, i loved it and i have a doubt.
    What should i do, If i want a slide show without clicking the start button, that is it start automatically when i load in to the url.

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    Comparing ` currentImageNumber === 8 ` will not work, because its string, not number.
    So really need only ` == ` And thats why adding numbers with string not works πŸ™‚ Really good lesson.

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    i want code for automatic photo scrolling that shows all the photos from image folder automatically and keeps on scrolling for notice board. please help me

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    <!DOCTYPE html>
    <html>
    <body>
    <img id="image" src="/Images/1.png" style="width: 150px; height: 150px" />
    <br />
    <input type="button" value="Start Slide Show" onclick="startImageSlideShow()" />
    <input type="button" value="Stop Slide Show" onclick="stopImageSlideShow()" />
    <script type="text/javascript">
    var intervalId;

    function startImageSlideShow()
    {
    intervalId = setInterval(setImage, 50);
    }

    function stopImageSlideShow()
    {
    clearInterval(intervalId);
    }

    function changeImage()
    {
    var imageSrc = document.getElementById("image").getAttribute("src");
    var currentImageNumber = imageSrc.substring(imageSrc.lastIndexOf("/") + 1, imageSrc.lastIndexOf("/") + 2);
    var newImage = "/Images/" + (Number(currentImageNumber) + 1) + ".png";
    // document.getElementById("result").innerHTML = newImage;
    document.getElementById("image").setAttribute("src", newImage);
    }
    </script>

    </body>
    </html>

    anyone tell me why this is not working please

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    i got that thanks for the explanation you are exceptionally good !!!!

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    i want the slideshow as soon as the webpage loads but not through start button how can i modify the above code

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    Can anyone clarifies this one. i didn't get output….?? whats going on???
    <html>
    <head>
    <img src="C:/Users/konas/Desktop/images/1.jpg" id="image" style="height:500px; width:650px"> </img>
    </br>
    <input type="button" value="startslideshow" onclick="startslideshow()"></input>
    <input type="button" value="stopslideshow" onclick="stopslideshow()"></input>
    <br> </br>
    <div id="result"> </div>
    <script type="text/javascript">
    var intervalid;
    function startslideshow(){
    intervalid = setInterval(changeImg, 500)
    }
    function stopslideshow(){
    clearInterval(intervalid);}

    function changeImg()
    {
    var imgSrc = document.getElementById("image").getAttribute("src");
    var currentimg = imgSrc.substring(imgSrc.firstIndexOf("/")+1, imgSrc.lastIndexOf("/")+2);
    var nimg = "/images/" + (Number(currentimg)+1) + ".jpg";
    document.getElementById("result").innerHTML = nimg;
    document.getElementById("image").setAttribute("src", nimg)
    }
    </script>
    </head>
    </html>

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    When an image is not shown on the page, it is quicker to right-click on the image to find it's URL, than to modify code to find what image URL was constructed.

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    How do i add links to the images?

    <—————————-

    var myImages=document.getElementById("slide");
    var imageArray=["images/slideshow/img1.jpg", "images/slideshow/img2.jpg", "images/slideshow/img3.jpg", "images/slideshow/img4.jpg", "images/slideshow/img5.jpg",];
    var imageIndex=0;

    function changeImage () {
    slide.setAttribute("src", imageArray [ imageIndex]);
    imageIndex++;
    if (imageIndex>=imageArray.length) {
    imageIndex=0;
    }
    }
    var intervalHandle = setInterval(changeImage,4000);

    var x=document.getElementById("videos");
    x.autoplay=false;
    x.load();

    <div id="slideshow">
    <img src="images/slideshow/img1.jpg" alt="kim" id="slide" />
    </div>

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    Very nice info and very good explanation., but this wont work for images more than 10.
    It needs a little modification of –
    currentImageNumber = imageSrc.substring(imageSrc.lastIndexOf("/") + 1, imageSrc.lastIndexOf("."));

    thanks for the Video tutorial.

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    you have done best tutorial on JS as long as my search…!!
    thank you so much,

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    I absolutely love how you show us the project you plan to make then you proceed to code it from scratch without already having the code planned out. Instead we get to see a side that most tutorials fail to show. We get to see the inner workings of how code progresses through trial and error. You are teaching us all so much more than the usual method of, "how to type perfected and refactored code" and instead showing us the evolution of code.

    This style of teaching is invaluable to beginners. When a beginner sees a standard tutorial the code is already perfect and without errors. But when beginners start to make their own projects and come across issues, we don't know what to do with them. Your teaching style shows us that these errors will occur normally and you showed us a little of how errors in code can be handled. Systematically and through repeated testing. Then when you were all done showing us the progression of the code you end the video by teaching us beginners how to refactor the code afterwards to make it more efficient.

    Nice work, and thank you very much.

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    I have coded a much simpler way. Try this, make sure you change your "img source folder and image names".
    <!DOCTYPE html>
    <html>
    <head>
    <title>Slide Show</title>
    <style>
    img{
    max-width: 100%;
    display: block;
    margin: auto;
    margin-top: 100px;
    }
    input[name="start"]{
    display: block;
    margin-left: 550px;
    margin-top: 10px;
    padding: 10px;
    background-color: green;
    color: white;
    border-radius: 10px;
    }
    input[name="stop"]{
    display: block;
    margin-left: 700px;
    margin-top: -40px;
    padding: 10px;
    background-color: red;
    color: white;
    border-radius: 10px;
    }
    </style>
    <script>
    var current = "e";
    var SlideId;
    function start(){
    SlideId = setInterval(change,1000);
    }
    function stop(){
    clearInterval(SlideId);
    }
    function change(){
    var pic = document.getElementById("pic");
    if(current=="e"){
    pic.src="img/lion.jpg";
    current = "l";
    }else if(current == "l"){
    pic.src="img/bear.jpg";
    current = "b";
    }else if(current == "b"){
    pic.src="img/fifa.jpg";
    current = "f";
    }
    else{
    pic.src="img/elephant.jpg";
    current = "e";
    }
    }
    </script>
    </head>
    <body>
    <img src="img/elephant.jpg" id="pic" height="400px" width="750px" onclick="change()"/>
    <input type="button" id="start" name="start" value="Start" onclick="start()"/>
    <input type="button" id="stop" name="stop" value="Stop" onclick="stop()"/>
    </body>
    </html>

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    i was trying how to make a slideshow for 3 days but now i am very clear because of you.thank you sir.

    Reply
  • May 21, 2019 at 5:26 pm
    Permalink

    Great Video as always, I request you to start a series for AngularJS tutorial aswell πŸ™‚ Thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *