Tim Gittos

I'm an Australian currently living in Austin, TX in the USA.

I currently earn a living programming, though I wouldn't call myself a programmer. If I had to attach a label to myself, I'd use the term autodidact.

I love learning, and my favorite things to learn about are programming, computer graphics, AI & machine learning, robotics, painting and creativity.

jQuery Context Menu Unbind Click Fix

Last updated on 09 Apr 2009

Updated on May 28, 2009, due to partial fix. The fix should now be a complete fix.

Apologies for the somewhat confusing title.
I’ve been doing a lot of jQuery work, replacing all the AJAX.NET crap in my project at work to speed the interface up. I’ve started using the awesome jQuery Context Menu plugin. However, I found it was also messing around with jsTree which I am using on the same page.

The problem is that the jQuery Context menu overzealously unbinds all click events from the document. This means that it’s going to break all your other Javascript that relies on clicking. Checking the documentation for jQuery’s unbind function, you can see that it accepts a function as a second parameter. This is the function that will be unbound if you pass that in as a parameter.
So, I fixed the jQuery Context Menu by changing the following:


  1. In the main contextMenu function, near the end, just above the return statement, I added the following:
    [javascript]
    // External click event for document
    function onDocumentClick(e) {
    var menu = $(‘#’ + o.menu);
    $(document).unbind(‘click’, onDocumentClick).unbind(‘keypress’);
    $(menu).fadeOut(o.outSpeed);
    return false;
    }
    [/javascript]

  2. Next, I change the function that assigns the click listener to the document to assign the defined function, instead of an anonymous function. So, change:
    [javascript]
    // Hide bindings
    setTimeout( function() { // Delay for Mozilla
    $(document).click( function() {
    $(document).unbind(‘click’).unbind(‘keypress’);
    $(menu).fadeOut(o.outSpeed);
    return false;
    });
    }, 0);
    [/javascript]
    to
    [javascript]
    // Hide bindings
    setTimeout(function() { // Delay for Mozilla
    $(document).click(onDocumentClick);
    }, 0);
    [/javascript]
  3. Lastly, I remove all instances of:
    [javascript]
    $(document).unbind(‘click’);
    [/javascript]

That’s it. That fixed the problem for me. You’ll notice I don’t bother with the keypress bindings. That’s because I’m not using them, so I’m not bothered. I’m assuming the fix for that will be a similar strategy, for those who are bothered.

I’ve uploaded my version for those who can’t get it working using the tips in this post, but remember the copyright remains with Cory S.N. LaViska over at A Beautiful Site.
jquery.contextMenu.js