views:

32

answers:

3

I have made the following javascript to be used in my jQuery based website. What it does, is to move a slider up/down, and scale the item above higher/smaller.

Everything works fine, but since the slider is only a few pixels in height, and the move event is a bit slow (it does not trigger for every pixel) so when I move the mouse fast, the slider can't hold on and the mouse get's out of the slider item. The mouseMove event won't be triggered no more since it is bound to the slider. I guess everything could be fixed by setting the mouseMove global to the whole site, but it won't work, or at least I don't know how to make that work. Should it be bound to document, or body?

here is my current code for the slider:

$.fn.resize = function (itemToResize) {

MinSize = 100;
MaxSize = 800;

pageYstart = 0;
sliderMoveing = false;
nuskriverHeight = 0;

this.mousedown(function(e) {
 pageYstart=e.pageY;
 sliderMoveing = true
 nuskriverHeight = parseFloat((itemToResize).css('height'));
});

this.mouseup(function() { 
 sliderMoveing = false 
});

this.mousemove(function(e) {
 if (sliderMoveing) { 
  (itemToResize).css('height', (nuskriverHeight + (e.pageY - pageYstart))); 
  if (parseFloat( (itemToResize).css('height')) > MaxSize) { (itemToResize).css('height', MaxSize) };
  if (parseFloat( (itemToResize).css('height')) < MinSize) { (itemToResize).css('height', MinSize) };
 };
}); 

};

Thanks for any help, is much appreciated

+1  A: 

Place the mouse events on the document

var $doc = $(document);

this.mousedown(function(e) {
  pageYstart=e.pageY;
  sliderMoveing = true
  nuskriverHeight = parseFloat((itemToResize).css('height'));

  $doc.mouseup(function() { 
    sliderMoveing = false ;
    $doc.unbind('mousemove mouseup')
  });

  $doc.mousemove(function(e) {
    if (sliderMoveing) { 
     (itemToResize).css('height', (nuskriverHeight + (e.pageY - pageYstart))); 
     if (parseFloat( (itemToResize).css('height')) > MaxSize) { (itemToResize).css('height', MaxSize) };
     if (parseFloat( (itemToResize).css('height')) < MinSize) { (itemToResize).css('height', MinSize) };
    };
  }); 

});
patrick dw
That did the trick, thanks :) Actually, that explain a lot more than just this specific problem for me :D Thank you!
Jacob Kofoed
A: 

Typically you watch for mousedown on the slider (to start the drag), and when you're dragging you watch for mousemove and mouseup (and keypress, if you want to allow Esc to cancel and such) anywhere on document.

T.J. Crowder
A: 

On mousedown, you should bind an event handler (on the document) to mousemove and mouseup.

In the mouseup handler, you should disconnect the two global handlers again.


However, it is possibly simpler to use the Draggable of jQuery UI: http://jqueryui.com/demos/draggable/

ignaZ