John Magnolia
John Magnolia

Reputation: 16793

detect jquery version use on or live

I am writing a plugin which can be used in any website where I dont know the exact version of jquery and getting a few issues with the .on() method.

To fix it I have something simple like this but still getting errors in jQuery 1.4.2.

var $myElements = $('.elements'),
    myFunction = function(e){
        console.log('here');
        e.preventDefault(); 
    }

if (typeof jQuery != 'undefined') {
    if(jQuery.fn.jquery < 1.4){
        $myElements.live('click', myFunction);
    } else {
        $(document).on('click', $myElements, myFunction);
    }
}

Upvotes: 0

Views: 119

Answers (2)

CodingIntrigue
CodingIntrigue

Reputation: 78525

You should bundle your own version of jQuery to save yourself a lot of hassle and a lot of redundant code. You can do this using noConflict to ensure that both your code and the code of the source website act independently:

<!-- load your jQuery -->
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
var yourjQueryVersion = $.noConflict(true);
(function($) {
    // Now you can use $ just like you normally would
    // And it will only execute against jquery-1.11.0
    $(function() {
        var $myElements = $('.elements'),
            myFunction = function(e){
            console.log('here');
            e.preventDefault(); 
        }
        $(document).on('click', $myElements, myFunction); // Yay!
    });
})(yourjQueryVersion);
</script>

This means that:

  • You don't need to write extra code for all jQuery version differences
  • If the target website upgrades to jQuery 2.0 (or similar), none of your code will break.
  • The source website might even be using a CDN, so there is a good chance only one copy of the jQuery library may be loaded due to caching.

Upvotes: 0

HarryFink
HarryFink

Reputation: 1010

Based on the previous answer, you can do this too:

;(function($) {
  if(!$.fn.on) {
    $.fn.on = $.fn.live;
  }
}(window.jQuery || window.Zepto));

Then you can use on in the rest of your code.

Upvotes: 2

Related Questions