0

As per last Rails gem update, my jQuery v was updated to 1.9 , which raises errors regarding my .live() bindings ...

$('#tags.tab-pane.active #tag-list li span.myTag').live "click", (e) ->

is now wrong .. I tried

$("#tags.tab-pane.active #tag-list li").on "click", "span.myTag", (e) ->

but it's wrong too... what should I use ? "on" or "delegate"

2 Answers2

3

if you are appending an element it is not in the dom originally but once it's been appended the below is applicable

$('body').on('click','#tags.tab-pane.active #tag-list li', function(e){
  //carry out function
}); 
Yusaf Khaliq
  • 3,033
  • 10
  • 37
  • 80
2

live has been deprecated for a while, and is no longer supported. You must use "on" http://api.jquery.com/on/

$("#tags.tab-pane.active #tag-list li").on("click", "span.myTag", (e) -//NOT WORKING

In order for that to work the "li" element must be present in the dom when this code is executed so that the event can be bound to it.

The equivalent implementation using "on" for how you were using live would be:

$(document).on('click','#tags.tab-pane.active #tag-list li span.myTag',function(){...})

You should try to use a "better or deeper in the dom" selector to bind the event to rather than document so that the event doesn't have to bubble all the way up the dom every time. Just remember that the selector you replace document with must be present when binding the event or else it will not work.

If you can figure out how to execute the code binding the event after the elements are in the dom, than you can bind the event directly on the element:

$('#tags.tab-pane.active #tag-list li span.myTag').on('click',function(){})

is equivalent to:

$('#tags.tab-pane.active #tag-list li span.myTag').click(function(){...})
Justin Bicknell
  • 4,716
  • 16
  • 25
  • As I am using jQuery with Rails and the assets pipeline.. this script is loaded with the application layout and the selector is not present. I guess I should insert this script into the corresponding Rails view , right ? –  Jan 23 '13 at 21:41
  • If the selector is not present when the script is run then you can attach the events to document, which is equivalent to using live. See the second code block in my answer... or if you can figure out how to execute the code once the elements are already on the page, than you can just use the regular click method.. will update my answer – Justin Bicknell Jan 23 '13 at 22:26