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);
});
You may try like this:
$(document).on("click",".readmore-anchor", showHiddenText);
$(document).on("click",".readless-anchor", hideShownText);
Live demo
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With