0
<button onclick="slider1.swapImage()">Function</button>

<p id="slide" width="400"></p>

<script language="JavaScript"> 

  var slider =function(){}

  slider.prototype.swapImage=function() 
  { 
    var path = new Array(); 
    var i = 0; 

    // Array of Content

    path[0] = "hello"; 
    path[1] = "hello1"; 
    path[2] = "hello2";

    document.getElementById("slide").innerHTML = path[i]; 

    if(i < path.length - 1) i++; 
    else i = 0; 

    setTimeout("swapImage()",2500); 
  };

  var slider1 = new slider;

</script>

"swapImage is not a function" Is the error i am facing and this is happening after the it has displayed the first element of the array.How to make the content slider display all the contents one by one?

Luuuud
  • 4,206
  • 2
  • 25
  • 34
Arun3x3
  • 193
  • 1
  • 7
  • 17

1 Answers1

0

The path and index properties should be defined on the slider class itself. Currently you initialize the list everytime the function is called!

The setTimeout Method also expects a function as argument. In your case the setInterval Method fits better. 'setInterval' vs 'setTimeout'

Why do you have the "swapImage is not a function" Error? That's because you reference to a global function called "swapImage", but you defined the method on the slider class so you have to use the this keyword. I think you are missing some basics about object oriented programming. That's a good starting point: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

I refactored the code: https://jsfiddle.net/9hh9v28x/12/

HTML

<button onclick="start()">start</button>
<p id="slide" width="400"></p>

Javascript

// Class Definition
var Slider = function() {
        // Array of Content
        this.path = ["hello1", "hello2", "hello3"];
    this.currentIndex = 0;
};

Slider.prototype.nextSlide = function() {
  // set text
  document.getElementById("slide").innerHTML = this.path[this.currentIndex]; 

  // count up index and set it back to 0 when the end of the "path" array is reached
  this.currentIndex++;
  if(this.currentIndex >= this.path.length){
    this.currentIndex = 0;
  }
};

// 
function start() {
    var slider1 = new Slider();

  // call method on start
  // otherwise you have to wait 2.5 secs to see something (wenn the setInterval() triggers)
    slider1.nextSlide();

  // The set interval method calls the given function
  // every given seconds (in this case 2.5)
  window.setInterval(function(){
    slider1.nextSlide();
  }, 2500);
}
Community
  • 1
  • 1
Daniel Bauer
  • 168
  • 2
  • 12