Arthur S.
Arthur S.

Reputation: 317

Different event for each click on same element

How Do I fire a new event for each click on a button. And how do I bring it in a loop, so after "click 3" it starts again with "click 1".

$('button').click(function () {

     //click 1
     cameraTween( camera.position, 1, 1, 1 );

     //click 2
     cameraTween( camera.position, 2, 2, 2 );

     //click 3
     cameraTween( camera.position, 3, 3, 3 );

});

Upvotes: 0

Views: 304

Answers (6)

Stryner
Stryner

Reputation: 7318

One solution is to make a generic function by using .one with recursion:

function LoopEvent(selector, event, calls /*array of functions*/) {
    $(selector).one(event, function() {
        // Execute Function
        calls[0](); 

        // Send current function to the back of the array
        calls.push(calls.shift());

        // Attach next event
        LoopEvent(selector, event, calls);
    });
}

Then you could call it like:

LoopEvent("button", "click", [
  function() { cameraTween( camera.position, 1, 1, 1 ); },  
  function() { cameraTween( camera.position, 2, 2, 2 ); },
  function() { cameraTween( camera.position, 3, 3, 3 ); }
]);

Example Fiddle

Upvotes: 2

Taytorious
Taytorious

Reputation: 324

Use a variable to track the clicks.

var clickCount = 1;
$('button').click(function () {
     if(clickCount > 3) {
       clickCount = 1;
     }

     cameraTween( camera.position, clickCount, clickCount, clickCount );
     clickCount++;
  });

Upvotes: 0

ryuu9187
ryuu9187

Reputation: 1172

// Create a variable one level higher than the scope of your click function
var clickCount = 0;

$('button').click(function () {
    clickCount++; // increment the count
    cameraTween(camera.position, clickCount, clickCount, clickCount);
    clickCount %= 3; // Reset every 3
});

Upvotes: 0

DVCITIS
DVCITIS

Reputation: 1037

var x = 0;

$('button').click(function () {
x = x++;

if (x==1){cameraTween( camera.position, 1, 1, 1 );}
else{
      if (x==2){cameraTween( camera.position, 2, 2, 2 );}
      else{
         cameraTween( camera.position, 3, 3, 3 );
      }
}
});

Upvotes: 0

Andrew Brooke
Andrew Brooke

Reputation: 12163

Create a variable and increment it in the click event

var i = 1;
$('#myButton').click(function () {
  if (i > 3)
    i = 1;
  cameraTween(camera.position, i, i, i);
  i += 1;
});

Upvotes: 1

VDanyliuk
VDanyliuk

Reputation: 1049

Use some variable to save click number and use switch to call different events based on this variable.

Upvotes: 0

Related Questions