Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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);

});​
like image 843
Enrique Moreno Tent Avatar asked Jul 14 '12 12:07

Enrique Moreno Tent


2 Answers

You may try like this:

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

Live demo

like image 68
Engineer Avatar answered Nov 03 '22 00:11

Engineer


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);
like image 32
Amith George Avatar answered Nov 03 '22 02:11

Amith George