0

I have the following function:

div_paper.onmousedown = function(event) { var mouseCoords = getCoords(event); startX = mouseCoords.x - offset[0]; startY = mouseCoords.y - offset[1]; rect = paper.rect(startX, startY, 0, 0); document.onmousemove = doDraw; // the function below i would like to fire once rect.drag(drag_move, drag_start, drag_up); }; 

which fires, as you can see, on every mousedown. I would like to fire the drag function only once, after the first mousedown. Should I use jQuery .one() for that?

Thanks in advance.

4
  • set a flag fired = false and then once the function is called once set the flag to true. Commented Jun 20, 2013 at 19:13
  • 1
    jQuery .one() should work fine for your purpose Commented Jun 20, 2013 at 19:14
  • Only once every time the event occurs, or once period? Commented Jun 20, 2013 at 19:18
  • once period! means after the first mousedown it should never fire again. Commented Jun 20, 2013 at 19:20

1 Answer 1

2

This is off the cuff, but you could try:

var dragged = false; div_paper.onmousedown = function(event) { var mouseCoords = getCoords(event); startX = mouseCoords.x - offset[0]; startY = mouseCoords.y - offset[1]; rect = paper.rect(startX, startY, 0, 0); document.onmousemove = doDraw; // the function below i would like to fire once if (!dragged) { dragged = true; rect.drag(drag_move, drag_start, drag_up); } }; 
Sign up to request clarification or add additional context in comments.

5 Comments

works flawless, don't know why i did not think about that. But is it better to use true or false instead of, lets say strings or numbers? is it better to calculate and you need less debugging?
@supersize If you're only looking for a "yes" or "no" value (which makes sense here, hence the use of true/false), then booleans are the way to go. That's kind of their purpose :).
then again one question, because i would not like to make a new post for that. When i want to "unbind" the mousedown, despite at which time. i could write div_paper.onmousedown = null; right? Its that kind of problem only knowing jQuery and not purely JS.
Event handlers attached with .bind() can be removed with .unbind(). (As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.) In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements: api.jquery.com/unbind So... div_paper.off('mousedown')
The boolean data type (true and false) is always the best choice for yes/no operations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.