jQuery append different text each click -
jQuery append different text each click -
i have basic jquery function going on:
$("#selector").click(function(){ $("#target").append("some text added..."); }); that works fine, except want append different text on each sequential click. example:
first click appends text "message 1" second click appends text "message 2" third click appends text "message 3"and on , forth...
also, set limit, say, 4 after 4 clicks, nil else happens.
any help appreciated.
var messages = [ 'first click appends text "message 1"', 'second click appends text "message 2"', 'third click appends text "message 3"' ]; var = -1; var target = $("#target"); $("#selector").click(function(){ target.append(messages[i = ++i % messages.length]); });
this "append" them. if wanted replace each message each time, you'd utilize .text() instead of .append().
demo (using .text()): http://jsfiddle.net/thvk6/
the i variable incremented each click. when i equal messages.length, reset 0.
so each click, i used grab new message array.
to farther explain increment trick, % modulo operator returns remainder when dividing i messages.length.
when i equal messages.length, remainder 0, we're start.
var = -1; first click:
++i; // 0 = % messages.length; // 0 messages[ ]; // first message (index 0) second click:
++i; // 1 = % messages.length; // 1 messages[ ]; // sec message (index 1) third click:
++i; // 2 = % messages.length; // 2 messages[ ]; // 3rd message (index 2) fourth click:
++i; // 3 = % messages.length; // 0, because 3 % 3 === 0 messages[ ]; // first message (index 0) ...and i 0 again, starts over.
so same increment trick, spelled out above be...
$("#selector").click(function(){ ++i; = % messages.length; target.append(messages[ ]); }); http://jsfiddle.net/thvk6/4/
jquery click append
Comments
Post a Comment