How jQuery 1.4 fixed rest of live methods

Neeraj Singh

By Neeraj Singh

on January 14, 2010

If you look at jQuery 1.3 documentation for live method you will notice that the live method is not supported for following events: blur, focus, mouseenter, mouseleave, change and submit .

jQuery 1.4 fixed them all.

In this article I am going to discuss how jQuery brought support for these methods in jQuery. If you want a little background on what is live method and how it works then you should read this article which I wrote sometime back.

focus and blur events

IE and other browsers do not bubble focus and blur events. And that is in compliance with the w3c events model. As per the spec focus event and blur event do not bubble.

However the spec also mentions two additional events called DOMFocusIn and DOMFocusOut. As per the spec these two events should bubble. Firefox and other browsers implemented DOMFocusIn/DOMFocusOut . However IE implemented focusin and focusout and IE made sure that these two events do bubble up.

jQuery team decided to pick shorter name and introduced two new events: focusin and focusout. These two events bubble and hence they can be used with live method. This commit makes focusin/focusout work with live method. Here is code snippet.

1if (document.addEventListener) {
2  jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
3    jQuery.event.special[fix] = {
4      setup: function () {
5        this.addEventListener(orig, handler, true);
6      },
7      teardown: function () {
8        this.removeEventListener(orig, handler, true);
9      },
10    };
11
12    function handler(e) {
13      e = jQuery.event.fix(e);
14      e.type = fix;
15      return jQuery.event.handle.call(this, e);
16    }
17  });
18}

Once again make sure that you are using focusin/focusout instead of focus/blur when used with live .

mouseenter and mouseleave events

mouseenter and mouseleave events do not bubble in IE. However mouseover and mouseout do bubble in IE. If you are not sure of what the difference is between mouseenter and mouseover then watch this excellent screencast by Ben.

The fix that was applied to map for focusin can be replicated here to fix mousetner and mouseleave issue. This is the commit that fixed mouseenter and mouseleave issue with live method.

1jQuery.each(
2  {
3    mouseenter: "mouseover",
4    mouseleave: "mouseout",
5  },
6  function (orig, fix) {
7    jQuery.event.special[orig] = {
8      setup: function (data) {
9        jQuery.event.add(
10          this,
11          fix,
12          data && data.selector ? delegate : withinElement,
13          orig
14        );
15      },
16      teardown: function (data) {
17        jQuery.event.remove(
18          this,
19          fix,
20          data && data.selector ? delegate : withinElement
21        );
22      },
23    };
24  }
25);

Event detection

Two more events are left to be handled: submit and change. Before jQuery applies fix for these two events, jQuery needs a way to detect if a browser allows submit and change events to bubble or not. jQuery team does not favor browser sniffing. So how to go about detecting event support without browser sniffing.

Juriy Zaytsev posted an excellent blog titled Detecting event support without browser sniffing . Here is the short and concise way he proposes to find out if an event is supported by a browser.

1var isEventSupported = (function () {
2  var TAGNAMES = {
3    select: "input",
4    change: "input",
5    submit: "form",
6    reset: "form",
7    error: "img",
8    load: "img",
9    abort: "img",
10  };
11  function isEventSupported(eventName) {
12    var el = document.createElement(TAGNAMES[eventName] || "div");
13    eventName = "on" + eventName;
14    var isSupported = eventName in el;
15    if (!isSupported) {
16      el.setAttribute(eventName, "return;");
17      isSupported = typeof el[eventName] == "function";
18    }
19    el = null;
20    return isSupported;
21  }
22  return isEventSupported;
23})();

In the comments section John Resig mentioned that this technique can also be used to find out if an event bubbles or not.

John committed following code to jQuery.

1var eventSupported = function (eventName) {
2  var el = document.createElement("div");
3  eventName = "on" + eventName;
4
5  var isSupported = eventName in el;
6  if (!isSupported) {
7    el.setAttribute(eventName, "return;");
8    isSupported = typeof el[eventName] === "function";
9  }
10  el = null;
11
12  return isSupported;
13};
14
15jQuery.support.submitBubbles = eventSupported("submit");
16jQuery.support.changeBubbles = eventSupported("change");

Next task is to actually make a change event or a submit event bubble if ,based on above code, it is determined that browse is not bubbling those events .

Making change event bubble

On a form a person can change so many things including checkbox, radio button, select menu, textarea etc. jQuery team implemented a full blown change tracker which would detect every single change on the form and will act accordingly.

Radio button, checkbox and select changes will be detected via change event. Here is the code.

1click: function( e ) {
2	var elem = e.target, type = elem.type;
3
4	if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
5		return testChange.call( this, e );
6	}
7},

In order to detect changes on other fields like input field, textarea etc keydown event would be used. Here it the code.

1keydown: function( e ) {
2	var elem = e.target, type = elem.type;
3
4	if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
5		(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
6		type === "select-multiple" ) {
7		return testChange.call( this, e );
8	}
9},

IE has a proprietary event called beforeactivate which gets fired before any change happens. This event is used to store the existing value of the field. After the click or keydown event the changed value is captured. Then these two values are matched to see if really a change has happened. Here is code for detecting the match.

1function testChange(e) {
2  var elem = e.target,
3    data,
4    val;
5
6  if (!formElems.test(elem.nodeName) || elem.readOnly) {
7    return;
8  }
9
10  data = jQuery.data(elem, "_change_data");
11  val = getVal(elem);
12
13  if (val === data) {
14    return;
15  }
16
17  // the current data will be also retrieved by beforeactivate
18  if (e.type !== "focusout" || elem.type !== "radio") {
19    jQuery.data(elem, "_change_data", val);
20  }
21
22  if (elem.type !== "select" && (data != null || val)) {
23    e.type = "change";
24    return jQuery.event.trigger(e, arguments[1], this);
25  }
26}

Here is the commit that fixed this issue.

1jQuery.event.special.change = {
2	filters: {
3		focusout: testChange,
4
5		click: function( e ) {
6			var elem = e.target, type = elem.type;
7
8			if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
9				return testChange.call( this, e );
10			}
11		},
12
13		// Change has to be called before submit
14		// Keydown will be called before keypress, which is used in submit-event delegation
15		keydown: function( e ) {
16			var elem = e.target, type = elem.type;
17
18			if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
19				(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
20				type === "select-multiple" ) {
21				return testChange.call( this, e );
22			}
23		},
24
25		// Beforeactivate happens also before the previous element is blurred
26		// with this event you can't trigger a change event, but you can store
27		// information/focus[in] is not needed anymore
28		beforeactivate: function( e ) {
29			var elem = e.target;
30
31			if ( elem.nodeName.toLowerCase() === "input" && elem.type === "radio" ) {
32				jQuery.data( elem, "_change_data", getVal(elem) );
33			}
34		}
35	},
36	setup: function( data, namespaces, fn ) {
37		for ( var type in changeFilters ) {
38			jQuery.event.add( this, type + ".specialChange." + fn.guid, changeFilters[type] );
39		}
40
41		return formElems.test( this.nodeName );
42	},
43	remove: function( namespaces, fn ) {
44		for ( var type in changeFilters ) {
45			jQuery.event.remove( this, type + ".specialChange" + (fn ? "."+fn.guid : ""), changeFilters[type] );
46		}
47
48		return formElems.test( this.nodeName );
49	}
50};
51
52var changeFilters = jQuery.event.special.change.filters;
53
54}

Making submit event bubble

In order to detect submission of a form, one needs to watch for click event on a submit button or an image button. Additionally one can hit 'enter' using keyboard and can submit the form. All of these need be tracked.

1jQuery.event.special.submit = {
2  setup: function (data, namespaces, fn) {
3    if (this.nodeName.toLowerCase() !== "form") {
4      jQuery.event.add(this, "click.specialSubmit." + fn.guid, function (e) {
5        var elem = e.target,
6          type = elem.type;
7
8        if (
9          (type === "submit" || type === "image") &&
10          jQuery(elem).closest("form").length
11        ) {
12          return trigger("submit", this, arguments);
13        }
14      });
15
16      jQuery.event.add(this, "keypress.specialSubmit." + fn.guid, function (e) {
17        var elem = e.target,
18          type = elem.type;
19
20        if (
21          (type === "text" || type === "password") &&
22          jQuery(elem).closest("form").length &&
23          e.keyCode === 13
24        ) {
25          return trigger("submit", this, arguments);
26        }
27      });
28    }
29  },
30
31  remove: function (namespaces, fn) {
32    jQuery.event.remove(
33      this,
34      "click.specialSubmit" + (fn ? "." + fn.guid : "")
35    );
36    jQuery.event.remove(
37      this,
38      "keypress.specialSubmit" + (fn ? "." + fn.guid : "")
39    );
40  },
41};

As you can see if a submit button or an image is clicked inside a form the submit event is triggered. Additionally keypress event is monitored and if the keyCode is 13 then the form is submitted.

live method is just pure awesome. It is great to see last few wrinkles getting sorted out. A big Thank You to Justin Meyer of JavaScriptMVC who submitted most of the patch for fixing this vexing issue.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.