Automatically Change Image On Some Interval In MVC 5 Using JavaScript

Here are the steps,

Step 1: Create basic project MVC with Controller, Model and View.

explorer

Step 2: Include required query libraries.
libraries

Step 3: Add image, next button and prev button. Also write JavaScript in the following way.

I have set interval as 3 seconds you may change as per your need.

  1. <script type="text/javascript">  
  2. function ChangeToNextImage()  
  3. {  
  4.     x = (x === imageArray.length - 1) ? 0 : x + 1;  
  5.     document.getElementById("img")  
  6.         .src = imageArray[x];  
  7. }  
  8.   
  9. function ChangeToPreviousImage()  
  10. {  
  11.     x = (x <= 0) ? imageArray.length - 1 : x - 1;  
  12.     document.getElementById("img")  
  13.         .src = imageArray[x];  
  14. }  
  15.   
  16. function startTimer()  
  17. {  
  18.     setInterval(ChangeToNextImage, 3000);  
  19. }  
  20. var imageArray = [],  
  21.     x = -1;  
  22. imageArray[0] = "/Content/Images/IMG_7785.jpg";  
  23. imageArray[1] = "/Content/Images/IMG_7788.jpg";  
  24. imageArray[2] = "/Content/Images/IMG_7790.jpg";  
  25. imageArray[3] = "/Content/Images/IMG_7799.jpg";  
  26. imageArray[4] = "/Content/Images/IMG_7847.jpg";  
  27. imageArray[5] = "/Content/Images/IMG_7849.jpg";  
  28. </script>  
  29. <br>  
  30. <br>  
  31. <br>  
  32. <br>  
  33.   
  34. <body onload="startTimer()">  
  35.     <fieldset style="margin: 8px;border: 1px solid;padding: 8px;border-radius: 4px;width: 430px; height: 230px;">  
  36.         <button type="button" onclick="ChangeToPreviousImage()" style="width:80px;height:200px">Previous</button> <img id="img" src="~/Content/Images/IMG_7785.jpg" height="200" width="200" />  
  37.         <button type="button" onclick="ChangeToNextImage()" style="width:80px;height:200px">Next</button>  
  38.     </fieldset>  
  39. </body>  
Code

Controls

Control

Step 4: Run the program and you will find that image automatically change,  also it is changing on next and prev button.
run

Hope you will understand how we can change the image in a specific interval automatically or next and previous button.