Search code examples
jquerycssjquery-eventsjquery-ui-draggablemousedown

When using jQuery ui draggable, :active code doesn't work


Here's my code, I try to make a dialog box draggable, and the button on it loses its :active functionality. I added the 'handle' option to draggable, didn't work. What am I doing wrong?

function Alert(text){
    var $Alert = $('<div/>').attr('id', 'Alert');
    $('body').append($Alert);
    
    $Alert.draggable({handle:"#Alert"});
    
    $Alert.append($('<div/>').attr('id', 'AlertText').text(text));
    $Alert.append($('<br/>'));
    $Alert.append($('<div/>').attr('id', 'AlertButton').text('OK'));
    
    $('#AlertButton').click(function(){
        $Alert.remove();
    });
}

Solution

  • Sorry guys, I am new so I couldn't answer myself at the time. I tried to post a comment but apparently it didn't show. I have found the answer myself, and stackoverflow.com is nice enough to even save the answer for me, so here it is: Though I searched google and StackOverflow a lot before posting, I found the answer here. Jquery Draggable UI overrides normal browser behavior for HTML elements inside draggable-enabled div

    You can disable dragging from the inner like this:

    $("#popup div").bind('mousedown mouseup', function(e) {
      e.stopPropagation();
    });
    

    event.stopPrpagation() stops a click on that inner from bubbling up to the outer that has the drag events bound to it. Since the event will never get there, those drag event handlers won't interfere. You can run this code before or after creating the draggable, it'll work either way.

    here's my current code in case it helps someone:

    function Alert(text){
        var $Alert = $('<div/>').attr('id', 'Alert');
        $('body').append($Alert);
    
        /*optional, requires jQuery ui .draggable()*/
        $Alert.draggable({handle:"#Alert"});
    
        $Alert.append($('<div/>').attr('id', 'AlertText').text(text));
        $Alert.append($('<br/>'));
        $Alert.append($('<div/>').attr('id', 'AlertButton').text('OK'));
    
        $("#AlertButton").bind('mousedown mouseup', function(e) {
            e.stopPropagation();
        });
    
        $('#AlertButton').click(function(){
            $Alert.remove();
        });
    }