Reputation: 8274
I am seeking to create an array that counts and keep tracks of clicks done to a certain area of the page; I would then like each amount of click to do something. Eg.) The 5th click a sound via mp3 triggers. The sixth click the page shakes.
How could I write an array to add different events per a number of clicks, assigning something to a specific number of clicks?
Upvotes: 1
Views: 139
Reputation:
Something like this!
var actions = {
5: 'playMusic',
6: 'shakeDiv'
},
actors = {
doNothing: function() {/*default action; do nothing;*/},
playMusic: function() {
alert('Your are about to here a music now');
/*place code for playing music here*/
},
shakeDiv: function() {
alert('page is about to shake');
/* place shake animation code here*/
}
},
defaultActionName = 'doNothing';//default action name
var clickCount = 0;
$('yourSelectorForThepart').click(function(e) {
clickCount++;
doAction();
});
function doAction() {
var actionName = actions[clickCount] || defaultActionName;
actors[actionName]();
}
And yes, you could just merge actions
& actors
. But i prefer this approach for maintenance & readability.
Upvotes: 1
Reputation: 206161
http://jsbin.com/izutav/1/edit
By simply creating an array of your events functions:
var a1_Events = [shake, noise, something],
a1_c = 0;
function shake(){
alert('SHAKING!');
}
function noise(){
alert('BZZZZZZZZZZZ!');
}
function something(){
alert('SOMETHING ELSE!');
}
$('#area1').click(function(){
a1_Events[a1_c++ % a1_Events.length]();
});
If you don't want to loop your events than use just: a1_Events[a1_c++]();
Upvotes: 1
Reputation: 6809
You could do it like this:
// put your click actions as functions here
var clickEvents = [function1, function2, function3, function4, playMP3, shakePage];
var clicks = 0;
// put your clickable object here
clickableObject.onclick = function(){
clickEvents[clicks]();
clicks++;
}
Upvotes: 0
Reputation: 3215
var clicks = 0;
$('a').click(function() {
switch(++clicks) {
case X:
/* do something */
break;
/* ... */
}
});
Or you can store functions in array
var myEvents = [function1, function2, function3];
var clicks = -1;
$('a').click(function() {
clicks++;
if(myEvents[clicks] != undefined) myEvents[clicks]();
});
Upvotes: 2