user3632044
user3632044

Reputation: 11

JQuery On and Live

I have a JavaScript file - MyJavascript.js - that is included in various web applications. The problem is that in one application I use JQuery v1.5.1, where the "Live" function works just fine, but in another application, since I use Bootstrap, I use v2.1.1., where "on" works and "live" doesn't.

Is there any way that I can write my JS file in a way that it works for Both the versions of JQuery?

++ Abhay

Upvotes: 1

Views: 212

Answers (3)

user3632044
user3632044

Reputation: 11

Thanks for the answers.

The problem of attaching the events to Dynamically Added elements still remained. So, I wrote down a Javascript function instead as follows :

function compatibleOn(event, selector, handler) {
  if (typeof jQuery().on === 'function') {
    $(document).on(event, selector, handler);
  } else {
    $(selector).live(event, handler);
  }
};

Upvotes: 0

rdubya
rdubya

Reputation: 2916

I believe you can use the delegate() function in both versions. Another option would be to test for the existence of the on() function in the jQuery object and create it if it is missing using either delegate() or live() inside your patched in function.

Here is an example of how to do that:

if(!$.fn.on) {
    $.fn.on = function(event, selector, handler) {
        if (arguments.length == 2) {
            return this.bind(event, selector);
        } else {
            return this.delegate(selector, event, handler);
        }
    };
}

Edited to support more of the on() functionality

Upvotes: 1

Fabian S.
Fabian S.

Reputation: 2529

You can always extend the jQuery object with your own functions to make things possible.

A solution for this problem would be the following function:

(function($) {
  $.fn.compatibleOn = function(event, handler){
    if(typeof jQuery().on === 'function')
    {
      $(this).on(event, handler);
    }
    else
    {
      $(this).live(event, handler);
    }
  }
})( jQuery );

You can now just call

jQuery('.my-link').compatibleOn('click', function(){alert('TEST');});

See http://jsfiddle.net/acs884t2/1/ for a working example.

Upvotes: 2

Related Questions