0

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 );

});

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;
});

1 Comment

I like this better than my answer. +1 for using the index in the function.
0

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

Comments

0
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 );
      }
}
});

1 Comment

There should be some logic to reset when the counter reaches a max limit.
0
// 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
});

Comments

0

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++;
  });

Comments

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.