Not sure how to use jQuery "live" since version 1.7

Here is a small snippet to show / hide text. The problem is that the click event does not fire for a "silent" class. Normally, I would use the jQuery live function, but since it is becoming obsolete in favor of on, I wonder how can I do this?

Here A jsfiddle: http://jsfiddle.net/SSAu2/

the code:

$(document).ready(function(){ var showHiddenText = function(e){ e.preventDefault(); var $this = $(this); $this.prev().fadeIn(); $this.text("less").removeClass("readmore-anchor").addClass("readless-anchor"); }; var hideShownText = function(e){ e.preventDefault(); var $this = $(this); $this.prev().fadeOut(); $this.text("more").removeClass("readless-anchor").addClass("readmore-anchor"); }; $(".readmore").after("<a href='#' class='readmore-anchor'>More</a>"); $(".readmore-anchor").on("click", showHiddenText); $(".readless-anchor").on("click", hideShownText); });​ 
+7
source share
2 answers

When the home ready function is executed, at that time there is no element that matches the ".readless-anchor" selector. The .on() method works, it needs one element to use as a parent. All events that occur in his descendants will bubble to the parent and will call the appropriate handler. That is why it is important that the jquery primary selector already exists.

From the documentation ,

Event handlers are bound only to the currently selected elements; They must exist on the page when your code makes a .on () call.

The second parameter for the .on() function is the selector with which to filter.

In your case, you can bind .on() to the body and filter your classes.

 $("body").on("click", ".readmore-anchor", null, showHiddenText); $("body").on("click", ".readless-anchor", null, hideShownText); 

This is sorting equivalent to what you could do using .live()

 $("body").find(".readmore-anchor").live('click', showHiddenText); 
+3
source

You can try the following:

 $(document).on("click",".readmore-anchor", showHiddenText); $(document).on("click",".readless-anchor", hideShownText); 

Live demo

+6
source

All Articles