Click hijacking in jQuery

Mike
@mikerfulcher on Twitter
6twenty on GitHub

Update November 11th, 2011: see my follow-up post for part 2, using jQuery special events and support for jQuery's new on/off event binding.


A long, long time ago, we were working on a project which involved fairly heavy use of ajax and 'click' event triggers in jQuery. At the time, this raised problems because in javascript, the 'click' event isn't always triggered from a normal left-click. I'm generally against hijacking all but normal left-clicks; I shouldn't be prevented from opening a link in a new tab just because it has a click event attached.

After some quick research I found this nice article by Mislav (@mislav). In it he demonstrates a simple method to hijack only normal left-click events, while letting all other click events (eg right-click or command-click) behave normally. After experiencing some odd behaviour in IE, I decided to package it all into a light jQuery plugin to keep my code nice & clean.

  1. (function($) {
  2. function unmodifiedLeftClick(e) {
  3. return e.which <= 1 && !e.metaKey && !e.shiftKey;
  4. };
  5. $.fn.liveLeftClick = function(callback) {
  6. return this.live('click', function(e) {
  7. if (unmodifiedLeftClick(e)) {
  8. callback.call(this, e);
  9. }
  10. });
  11. }
  12. $.fn.bindLeftClick = function(callback) {
  13. return this.bind('click', function(e) {
  14. if (unmodifiedLeftClick(e)) {
  15. callback.call(this, e);
  16. }
  17. });
  18. }
  19. $.fn.delegateLeftClick = function(selector, callback) {
  20. return this.delegate(selector, 'click', function(e) {
  21. if (unmodifiedLeftClick(e)) {
  22. callback.call(this, e);
  23. }
  24. });
  25. }
  26. })(jQuery);

The functions match the existing bind, delegate and live methods of event binding in jQuery (and could be extended to support jQuery 1.7's new on methods). Usage is almost exactly the same as usual, except that you don't need to specify the event:

  1. $('#ajax-container a').bindLeftClick(function(e) {
  2. e.preventDefault();
  3. });
  4. $('#ajax-container').delegateLeftClick('a', function(e) {
  5. e.preventDefault();
  6. });
  7. $('#ajax-container a').liveLeftClick(function(e) {
  8. e.preventDefault();
  9. });

Posted Nov 9th, 2011. Tagged javascript, jquery


blog comments powered by Disqus



© 2011 rawnet.com