Search code examples
javascriptfirefoxright-clickstoppropagation

Right click keeps propagating in Firefox


I just noticed something unusual. This is what I want to accomplish:

  • I want a div to be shown when I click a link

  • I want the div to disappear when I click somewhere else in the document

  • I don't want it to disappear when I click the div itself

Something like this:

http://jsfiddle.net/XPmyF/

JS:

(function() {
    var box = $('#box');
    $(document).on('click', function() {
        if (box.css('display') == 'block') {
            box.css('display', 'none');
        }
    });
    $('#start').on('click', function(e) {
        box.css({
            'text': 'Box',
            'position': 'absolute',
            'top': '50px',
            'left': '0',
            'background': '#EEE',
            'border': '1px solid #555',
            'width': '200px',
            'height': '50px',
            'display': 'block'
        });
        e.stopPropagation();
    });

    box.on('click', function(e) {
        e.stopPropagation();
    });
})();​

That fiddle works just fine but when I tested that in Firefox (15.0.1), if you right-click on the div, it dissapears, which is not the behavior I'm looking for. It seems that stopPropagation() works for clicks but not right-clicks in Firefox. Chrome keeps right-clicks from propagating to the document.

How can I fix it?

Thanks


Solution

  • Use the event.which method to detect which button was clicked. Here's an example in jsfiddle.

    $(document).on('click', function(event) {
        if (event.which == 1 && box.css('display') == 'block') {
            box.css('display', 'none');
        }
    });