jQuery live() shim for jquery-migrate 3+

jQuery version 3+ removed jQuery’s function $.live() and if you are using some old CMS/shopping cart (like Interspire) that doesn’t upgrade their JavaScript functions, upgrading jQuery 3+ could lead to break your site.

jQuery.live() for jQuery 3+

All we need to do is, use .on() function write wrapper for .live()

jQuery on() function takes “event value” and “child selector” as string, while old live function could take object to chain it to live() function. So, old code could break if we don’t supply object selector as string.

Also live() function was dependent on properties like “$.selector” & “$.context”. However, jQuery library 3+ also removed properties like “selector” and “context” which are required for legacy live function. So we need to make some workaround to create those properties. “.selector” for .live() could be created by string read selector’s ID while “.context” could be done by using selector’s parent() object.

jQuery.fn.live = function( types, data, fn ) {
	
	try{
	  if(typeof(this.selector) == "undefined" && typeof(this[0].id) != "undefined"){
		this.selector = String("#" + this[0].id);
	  }
	}catch(e){
        }	

	if(typeof(this.context) == "undefined"){
		this.context = jQuery(this).parent();
	}

	jQuery( this.context ).on( types, this.selector, data, fn );
	return this;
};

Code Pen Demo:-

See the Pen
jQuery Live for 3+
by vikaskbh (@vikaskbh)
on CodePen.

jQuery Browser property for jQuery 3+

jQuery 3 also removed $.browser property. So, some old code might break on third-party CMS. I’ve used jQuery migrate 1+ to append it to existing jquery-migrate 3+.

if (!jQuery.browser) {
    var uaMatch = function(a) {
        a = a.toLowerCase();
        a = /(chrome)[ \/]([\w.]+)/.exec(a) || /(webkit)[ \/]([\w.]+)/.exec(a) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a) || /(msie) ([\w.]+)/.exec(a) || 0 > a.indexOf("compatible") && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a) || [];
        return {
            browser: a[1] || "",
            version: a[2] || "0"
        }
    };
    matched = uaMatch(navigator.userAgent);
    browser = {};
    matched.browser && (browser[matched.browser] = !0, browser.version = matched.version);
    browser.chrome ? browser.webkit = !0 : browser.webkit && (browser.safari = !0);
    jQuery.browser = browser
};

Just append above two snippets in one of your own hosted jquery-migrate file and it should fix the issue related them.

Video Explanation of this article

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

RequireJS example – loading desktop vs mobile javascript libraries and overriding functions

Next Post

How to enable dark mode in shopify admin even before they release that feature in 2022

Related Posts