Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect mouseup outside of mousedown element

I am trying to detect when the mouseup (mouse button released) occurs outside of the element that the mousedown event was triggered on. I have several buttons that I alter the CSS (by using classes) with a mousedown (button press) and completion of click (mousedown+mouseup). Problem is that if you click on the element then release the mouse button outside of the element, that the mouseup does not fire. I've also tried capturing a general "mouseup" event on the document to "reset" the classes assigned to the element and that does not seem to work either.

Here is a sample HTML:

<div class="qbuttons">
<a id="qb_appointments" href="#" class="appointments"><div>
Schedule a Service<br />
Appointment</div></a>
</div>

Here is the jQuery that I am using to fiddle with the element:

var current_qbutton = "";

$('.qbuttons a').mousedown(function() {
    current_qbutton = $(this).attr('id');
    $(this).addClass('active');
});

$('.qbuttons a').click(function() {
    $(this).removeClass('active');
});

$('*').mouseup(function(event) {
    event.stopPropagation();
    alert(current_qbutton);
    if(current_qbutton != "") {
        $('#' + current_qbutton).removeClass('active');
        current_qbutton = "";
    }
});

I've tried different selectors for the mouseup -- document, window, ‘body *’, ‘html ’ and ‘’ -- from what I am seeing it appears that the mouseup is not firing on release of the mouse button outside of the mousedown element, because the alert does not happen.

like image 684
Rob Emenecker Avatar asked Jul 02 '13 22:07

Rob Emenecker


1 Answers

The reason that this is not working is due to the anchor element (which does not seem to be serving a purpose). You can remove the a and replace it with a div or span or whatever else you like and then the mouseup event can be fired outside of the element.

This seems to be working for me. http://jsfiddle.net/FXnsx/3/

var current_button;
$('.test').on('mousedown', function(){
    current_button = this.id;
});
$(document).on('mouseup', function(){
    alert(current_button);
});
like image 170
Joe Avatar answered Sep 27 '22 18:09

Joe