Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of an element within a live function

Tags:

jquery

I'm creating new < li > elements with a live() click function, but jquery won't tell me the index of newly created elements. Here's the code:

    $esl = $('.dynamicLink');
    $esl.live('click',function(){
        var dynamicIndex = $esl.index(this);
        alert(dynamicIndex);
    });

Whenever I click the dynamicLink, it returns "-1" as the index. Any suggestions?

like image 230
bjork24 Avatar asked Sep 07 '09 19:09

bjork24


1 Answers

Because live uses event delegation to "bind" events to future elements, you need to call index on an up-to-date list of elements. Try this:

$esl = $('.dynamicLink');
$esl.live('click',function(){
    var dynamicIndex = $('.dynamicLink').index(this);
    alert(dynamicIndex);
});
like image 62
Joel Avatar answered Nov 29 '22 16:11

Joel