0

I am trying to understand JavaScript modules. As such I am using that pattern, or at least I think it is that pattern to cycle through an array on click.

Each click should display the next value in the array.

When the last value in the array has been reached and the click is registered again the cycle should start over.

The page will load, displaying the value at the start of the array.

For instance, the array contains ['green','yellow','red']

Page loads = value displayed is green

click = value displayed is yellow

click = value displayed is red

click = value displayed is green

and so on.

Here is a Fiddle of what I have so far: http://jsfiddle.net/TYj3p/

Here is the HTML:

<p>The color is <span id="print"></span>.</p>

Here is the JavaScript that I have but I am suck on the click part:

var s;
var ele;

Next = {

  settings : [
      {color : 'green'},
      {color : 'yellow'},
      {color : 'red'}
  ],

  elements : {
       span : $('#print')
  },

  init : function() {
      //kick things off
      s = this.settings;
      ele = this.elements;
      this.bindUIActions();
  },

  bindUIActions : function() {
      ele.span.ready(function() {
          Next.loadText();
      });
      ele.span.on('click', function() {
          Next.changeText();
      });
  },

  loadText : function() {
      ele.span.text(s[0].color);
  },

  changeText : function() {
      var i = 0;
      ele.span.text(s[i].color);
      i++;
  }

};

(function() {
    Next.init();
})();

1 Answer 1

1

Take a look at this demo: http://jsfiddle.net/TYj3p/7/

Add a button and call changeText on onClick method.

<button onclick="Next.changeText();">Click</button>

On you changeText function check the index of current color and if it is the last element show the first one. Your changeText function should be something like this:

changeText : function() {
    var index = Next.indexOfColor(ele.span.text());
    if(index < s.length-1) {
        ++index;
        ele.span.text(s[index].color);
    } else {
        ele.span.text(s[0].color);
    }
},

Add this function to return the index value of the current color.

indexOfColor: function (color) {
    for(var i=0; i < s.length; i++) {
       if(s[i].color == color) 
           return i; 
    }
    return -1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I am just trying to learn how to write a JavaScript Module, this really helps. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.