Reputation: 25247
Here a small snippet to show/hide text. The problem is that the click event doesn't fire for the "readless" class. Usually I would have use the "live" function of jQuery, but since its being deprecated in favor of "on", I wonder how should I do it?
Here's A jsfiddle: http://jsfiddle.net/SSAu2/
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);
});
Upvotes: 7
Views: 176
Reputation: 5916
When the dom ready function executes, at the time there doesnt exist any element that matches the selector '.readless-anchor'. The way .on()
works is, it needs one element to use as a parent. All events that occur under its descendants will bubble uptill the parent and will call the appropriate handler. Which is why its important that the primary selector for jquery already exist.
From the documentation,
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
The second parameter to the .on()
function is the selector to filter with.
In your case, you could anchor the .on()
on body
and filter by your classes.
$("body").on("click", ".readmore-anchor", null, showHiddenText);
$("body").on("click", ".readless-anchor", null, hideShownText);
This is sort off equivalent to what you might have done using .live()
$("body").find(".readmore-anchor").live('click', showHiddenText);
Upvotes: 3