scferg5
scferg5

Reputation: 2013

jQuery append different text each click

I have a basic jQuery function going on:

$("#selector").click(function(){
    $("#target").append("Some text to be added...");
});

That works fine, except I want to append different text on each sequential click. For example:

  1. First click appends text "Message 1"
  2. Second click appends text "Message 2"
  3. Third click appends text "Message 3"

and so on and so forth...

Also, I would like to set a limit, to say, 4 which after 4 clicks, nothing else happens.

Any help would be appreciated.

Upvotes: 0

Views: 619

Answers (3)

user1106925
user1106925

Reputation:

var messages = [
  'First click appends text "Message 1"',
  'Second click appends text "Message 2"',
  'Third click appends text "Message 3"'
];

var i = -1;

var target = $("#target");

$("#selector").click(function(){
    target.append(messages[i = ++i % messages.length]);
});

This will actually "append" them. If you wanted to replace each message each time, you'd use .text() instead of .append().

DEMO (using .text()): http://jsfiddle.net/thVK6/

The i variable will be incremented with each click. When i is equal to messages.length, it will be reset to 0.

So with each click, i is used to grab a new message from the Array.


To further explain the increment trick, the % modulo operator returns the remainder when dividing i by messages.length.

When i is equal to messages.length, the remainder is 0, so we're back to the start.

var i = -1;

First click:

++i; // 0
i = i % messages.length; // 0

messages[ i ]; // first message (index 0)

Second click:

++i; // 1
i = i % messages.length; // 1

messages[ i ]; // second message (index 1)

Third click:

++i; // 2
i = i % messages.length; // 2

messages[ i ]; // third message (index 2)

Fourth click:

++i; // 3
i = i % messages.length; // 0, because 3 % 3 === 0

messages[ i ]; // first message (index 0)

...and so i is now 0 again, so it starts over.


So the same increment trick, but spelled out as above would be...

$("#selector").click(function(){
    ++i;
    i = i % messages.length;

    target.append(messages[ i ]);
});

http://jsfiddle.net/thVK6/4/

Upvotes: 2

HandiworkNYC.com
HandiworkNYC.com

Reputation: 11114

reference: http://jsfiddle.net/HDUAK/2/

<div id="selector">Select</div>
<div id="target">Target</div>


var i = 1;
$("#selector").click(function(){
    if(i > 4) {return false} else {
         $("#target").append("Message"+i);
    }

    i++;
});

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 186083

One possibility:

(function () {
    var messages, i;

    i = 0;
    messages = [
        'Message 1 ... ',
        'Message 2 ... ',
        'Message 3 ... '
    ];

    $( elem ).click( function () {
        if ( i === messages.length ) { i = 0; }
        $( target ).append( messages[ i ] );
        i += 1;
    });
}());

Live demo: http://jsfiddle.net/RhBAh/

Upvotes: 1

Related Questions