MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

jQuery plugin bind to dynamically created element

Following sample plugin does not work on dynamically created element.

See JSFIDDLE

$.fn.getData = function() {
    return this.click(function() {
        alert($(this).data("aloc"));    
    }); 
};

$("a").getData();

I can do it using jQuery.livequery plugin as

$("a").livequery(function() {
    $(this).getData();
});

But want to do this facility without livequery in my plugin

Upvotes: 2

Views: 883

Answers (4)

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

A solution can be jsfiddle

$.fn.getData = function() {
    return $(document).on('click',this.selector,function() {
        alert($(this).data("aloc"));    
    }); 
};
$("a").getData();

Upvotes: 0

Amin Jafari
Amin Jafari

Reputation: 7207

the problem is that you are not setting an event listener to the dynamically created element, and you know what happens when you don't! nothing happens and it wont get triggered, so try changing your plugin code a bit:

$.fn.getData = function() {
    var tagName=$(this).prop("tagName"); //if you wanna get the element by tagname
    var elemID='#'+$(this).attr("id"); //if you wanna get the element by id
    var elemClass='.'+$(this).attr("class"); //if you wanna get the element by class
    return $(document).bind('click','put tagName or elemID or elemClass based on your needs here',function() {
        alert($(this).data("aloc"));    
    }); 
};

$("a").getData();

now it gives you the result you want.

UPDATE: or you can simply use:

$.fn.getData = function() {
    return $(this).bind('click',function() {
        alert($(this).data("aloc"));    
    }); 
};

$("a").getData();

Upvotes: 0

dreamweiver
dreamweiver

Reputation: 6002

Well for delegated events you need to use .on() as per jQuery 1.7 and after . here you go i have modified your code as below and its working as you intend to.

Jquery Code:

//plugin
$.fn.getData = function () {
   return $(document).on('click', 'a', function () {
      alert($(this).data("aloc"));
   });
};

Live Demo:

http://jsfiddle.net/dreamweiver/MSkm6/9/

Happy Coding :)

Upvotes: 2

Nhat Nguyen
Nhat Nguyen

Reputation: 21

You can add .getData() after define a tag. It will work.

//create new element
$("#NewElement").click(function(){
    var n = $('a').length+1;
    $("<a href='#' data-aloc='a"+n+"'>New Test "+n+"</a><br />").getData().insertBefore($(this));
});

Upvotes: 0

Related Questions