34

How can I create an event in JQuery triggered when the mouse is down and moving? And only triggered once each mousedown + mousemove?

  • I'm encountering this very problem today. Apparently, with Firefox, we're just screwed? The document.mouseup doesn't work either. – Ducain Jan 06 '11 at 18:00

13 Answers13

61

Updated:

So, it looks like if your mouse is no longer over the element on which onmouseup is bound, it won't see the mouse up event. Makes sense, when you stop and think about it, but when the mousedown event happens over the element, we expect, as UI users, for it to know when it was released (even if it isn't over the element).

So, to get around this, we actually detect the mouseup on the document level.

var clicking = false;

$('.selector').mousedown(function(){
    clicking = true;
    $('.clickstatus').text('mousedown');
});

$(document).mouseup(function(){
    clicking = false;
    $('.clickstatus').text('mouseup');
    $('.movestatus').text('click released, no more move event');
})

$('.selector').mousemove(function(){
    if(clicking == false) return;

    // Mouse click + moving logic here
    $('.movestatus').text('mouse moving');
});

I tried this out on jsbin, and it seems to work. Check it out here: http://jsbin.com/icuso. To edit it (see the JS and HTML), just tag "edit" on the end of the URL. http://jsbin.com/icuso/edit.

Matt
  • 41,216
  • 30
  • 109
  • 147
  • the problem is that the mouseup doesn't seem to be triggered after I have dragged the mouse, then the clicking isn't reset –  Oct 15 '09 at 14:41
  • How interesting - I didn't realize that. I just tested it on FF3.5 and it is as you say. Which browser are you using? – Matt Oct 15 '09 at 15:00
  • Yeah, its firefox. And it gets worse. I'm working with drag and drop from an iframe and out to the parent. So I guess I'll need a mouseup trigger in the parent aswell, which will trigger mouseup in the iframe. I'll try this –  Oct 15 '09 at 15:12
  • I can't get my iframe or the parent to catch the onmouseup.. Wierd –  Oct 15 '09 at 15:25
  • @Persmon 3 years too late but if you want mouseup to work on iframes (and the belong to the same domain) all you have to do is replace $(document) with $('iframe').map((i, e) => e.contentWindow.document).add(document) – Ivan Castellanos Nov 09 '18 at 05:45
44

use following code

$(element).mousemove(function(e){
 if(e.which==1)
 {
   #do job
 }
});

Update :
For some browsers you may want to use this :

$(element).mousemove(function(e){
 if(e.buttons==1)
 {
   #do job
 }
});
M Rostami
  • 4,035
  • 1
  • 35
  • 39
8

I did the following for an audio volume controller:

$('#control-vol').bind('mousedown', function(e){
    $('#control-vol').bind('mousemove', function(e){
        var volumen = e.pageX - this.offsetLeft;
        $('#barra-vol').width(volumen + 'px');
        $('audio')[7].volume = volumen/50;
    });

    $('#control-vol').bind('mouseup',function(){
        $('#control-vol').unbind('mousemove')
    });
});
Littm
  • 4,923
  • 4
  • 30
  • 38
1
document.onmousedown = function(e) {
    e = e || window.event;
    var button = (type e.which != "undefined") ? e.which : e.button;
    if (button == 1) {
        alert("Left mouse button down");
    }
};

javascript event e.which?

Community
  • 1
  • 1
Nonesome
  • 98
  • 1
  • 1
  • 7
1
$("element").mousedown(function () {
    $(this).mousemove(function () {
        console.log("OK Moved!");
    });
}).mouseup(function () {
    $(this).unbind('mousemove');
}).mouseout(function () {
    $(this).unbind('mousemove');
});
niraj
  • 11
  • 2
1

This might help the situation... there is some difficulty when dealing w/ iframes. I'm currently working on a project needing to resize elements in an iframe.

Say you have an iframe with an id of 'iframe'. I have only tested this in FF, but it's working:

var $iframe = $('#iframe');
$iframe.load(function()
{
  var $body = $iframe.contents().find('HTML');
  /* ...bind your events here to $body.. */
  $body.mousedown(function(){...});
  $mody.mouseup(function(){...});
}

I try to bind everything to the document, or in this case, to the iframe's document, and then when an event happens, I call a function that determines what exactly was the target. Keep in mind that jQuery has a pretty cool feature in that you can wrap the event target in a jQuery function:

$(selector).click(function(e)
{
  var id = $(e.target).attr('id');
});

Hope this helps! And I hope it works in the other browsers or I'm going to be really frustrated in a few days :o

1

The answer can be found in another SO topic:
Firefox drags div like it was an image

You need to return false from the event handlers to prevent the default action

Once I put a return false in my event handlers, it worked like a charm.

Pang
  • 9,564
  • 146
  • 81
  • 122
Ducain
  • 1,581
  • 3
  • 18
  • 27
1

For anyone else coming to this thread in search of generic assistance for jQuery mouseup, mousemove and mousedown using dynamically loaded content, I found (In chrome at least) this modification of Matt's post to be functional:

var clicking = false;

$('.selector').live("mousedown",function(){
    clicking = true;
    $('.clickstatus').text('mousedown');
});

$(document).live("mouseup",function(){
    clicking = false;
    $('.clickstatus').text('mouseup');
    $('.movestatus').text('click released, no more move event');
})

$('.selector').mousemove(function(){
    if(clicking == false) return;

    // Mouse click + moving logic here
    $('.movestatus').text('mouse moving');
});

http://api.jquery.com/live/ jQuery $.live() binds to all present and future elements, so if you need to add a mousemove and mousedown to a dynamically created element, this should work (again, in chrome at least).

Community
  • 1
  • 1
ArkahnX
  • 405
  • 1
  • 5
  • 9
0
setTimeout(function(){

  var radiobox_state;
  $('input[type="radio"]').mousedown(function(){
    radiobox_state=this.checked
  })

  $('input[type="radio"]').click(function(){
    if(radiobox_state){
      $(this).prop("checked",false);
    }
  })
  
}, 500);
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 13 '21 at 10:38
-1
e.preventDefault();

and e is the event handler you pass to the function

j0k
  • 22,600
  • 28
  • 79
  • 90
KoleS
  • 7
  • 1
-1
$(document).on('mousedown', function() {
    $(document).bind('mousemove', function() {
        $('#id-name').dosomething();
    });
});


$(document).on('mouseup', function() {
    $(document).unbind('mousemove');
});
djrconcepts
  • 635
  • 5
  • 6
-2

we use $.bind() like this:

$('#div').bind('mousemove mousedown', function(){});

This mean either mousemove or mousedown fired, the function would execute. so in the function, we still able to check if left button is press by using event.which equal to 1. so the code should look like this:

$('#div').bind('mousemove mousedown', function(e){
        if(e.which == 1){
            //let the fun begin
        }
    });
Ratha Hin
  • 37
  • 1
  • 6
-3

May be:

$('input').mousedown(function{
    $('input').mousemove({
      etc
    });
});

but for some reason i think you already tried that..

Noam Smadja
  • 915
  • 2
  • 8
  • 29
  • ok, so $('input').bind('mousedown mousemove', fn); will only fire when the mouse is pressed down AND moving? I thought this would fire if the mouse is pressed down OR moving. –  Oct 15 '09 at 14:07