سؤال

I have a button that makes a div move on the page, but I want for the button to make it move only once. If the user keeps clicking the button right now, the div keeps moving in the same direction.

هل كانت مفيدة؟

المحلول

A simple and general way might be just setting a flag.

var box_can_move = true;
$('button_id').on('click', function(event, element){
    if(box_can_move){
        box_can_move = false;
        //move box;
    }
});

As alluded by clockworkgeek's comment, a big advantage of having a flag is being able to manipulate and inspect the state (of wether the box has already moved or not) directly without coupling it with the event handling logic.

نصائح أخرى

If you have the ability to use jQuery, this is simple with the one() method:

$('yourButtonId').one('click', 
    function(event) 
    { 
        alert('This will only execute once.'); 
    });

try it

  $('button_id').on('click', function(event, element){
   new Effect.Move('div', {x: 300});
   element.stopObserving();
  });

example http://jsfiddle.net/pJ9cf/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top