Search code examples
jquerydraggablemouseup

Jquery draggable - mouseup not firing when cursor leaves object


I created a draggable object that allows me to hide and show content when the object is dragged from left to right (to hide) then right to left (to show). The object can't go any further than left or right (containment:"parent"). The event is fired on mouseup. However, the mouseup only works if the mouse cursor stays on the object. If the mouseup event is fired when the cursor has left the object, it doesn't fire.

Can someone help me find a way to trigger the mouseup even if the cursor has left the object? ANy help would be much appreciated. Here's a demo: http://www.madfrogdesigns.com/vault/mouseup/

This is my jquery code:

$(document).ready(function(){
    initCheckBoxes();
});

var slideSpeed = 200;
var leftDist = 20;

function initCheckBoxes()
{
    $(".toggle-slider").draggable({containment: "parent"});
    $(".toggle-slider").mouseup(function(){

    //Toggle markers;
    $(".content").fadeToggle(200);

    var status = $(this).attr("toggle-status");

    switch(status)
        {
            case "0":
            $(this).animate({left: leftDist}, slideSpeed);
            $(this).attr("toggle-status", "1");
            break;

            case "1":
            $(this).animate({left: "0"}, slideSpeed);
            $(this).attr("toggle-status", "0");
            break;
        }
    });
}

Solution

  • You need two separate events since if the mouseup occurs outside of the element it won't originate from there:

    function initCheckBoxes()
    {
        $(".toggle-slider").draggable({containment: "parent"});
    
        var slideMouseDown = false;
    
        $('.toggle-slider').mousedown(function() {
          slideMouseDown = true;
        });
    
    
        $(document).mouseup(function() {
    
          if(slideMouseDown == true)
          {
            //Toggle markers;
            $('.content').fadeToggle(200);
    
            var sliderToggle = $('.toggle-slider');
            var status = sliderToggle.attr('toggle-status');
    
            switch(status)
            {
              case "0":
              //its off, slide it by 20px;
              sliderToggle.animate({left: leftDist}, slideSpeed);
              //change status to 1
              sliderToggle.attr("toggle-status", "1");
              break;
    
              case "1":
              //its 'on', slide it to 0px;
              sliderToggle.animate({left: "0"}, slideSpeed);
              //change status to 0
              sliderToggle.attr("toggle-status", "0");
              break;
            }
          }
    
          slideMouseDown = false;
        });
    }