0

Until now, I've been relying upon the default rails 4 jQuery gem for all my jQuery needs gem 'jquery-rails'. However, for a new enhancement to my app I wanted to use jQuery .live() function but seems that's only available 1.3~. Should I just manually install the version of jQuery I want rather than include it as a gem? What's the best way to specify which jQuery version I want?

1 Answer 1

4

The .live() method is deprecated as of jQuery 1.7+

Solution:

See VERSION.md to see which versions of jquery-rails bundle which versions of jQuery. For instance you could use any jquery-rails gem prior to version 1.0.17 and everything will work fine. For example:

gem 'jquery-rails', '1.0.16'  # This match the jQuery version 1.6.4

That said, you should use always the latest version of jQuery because every iteration provides a lot of bugfixes and better cross-browser compatibility. See below how to handle this.

Further reading:

As of jQuery 1.7+ you should use .on() to atach event handlers. The documentation even recommends for older version of jQuery the use of .delegate() in preference to .live()

Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.

Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+

If you want to improve your knowledge about the subject please, continue reading the official documentation of the old .live() method and the new .on() method.

A conversion example:

The following three method calls are functionally equivalent:

$( "a.offsite" ).live( "click", function() {
  alert( "Goodbye!" ); // jQuery 1.3+
});
$( document ).delegate( "a.offsite", "click", function() {
  alert( "Goodbye!" ); // jQuery 1.4.3+
});
$( document ).on( "click", "a.offsite", function() {
  alert( "Goodbye!" ); // jQuery 1.7+
});
2
  • Using on(), if I update the HTML in the DOM does it re-assign the events I assigned on the first page load automatically (like live() seems to do)? Or should I write a line of code to do this after HTML is updated in the DOM? I couldn't see if this was the case in the documentation.
    – Martyn
    Mar 30, 2014 at 5:22
  • I'm almost sure that it does since the behavior are pretty the same. However read the .on() doc updated in the post and see if it works. If you want, create a jsfiddle to hack on it. Let me know if you have luck. Mar 30, 2014 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.