user2653125
user2653125

Reputation: 185

jQuery Plugin not working for all elements that is applied upon

Consider the following jQuery Plugin code:

(function($){
$.fn.MyPluginMethod= function() {
    $(this).after('<span>Hello</span>');
    };
})(jQuery);

if we call this function like this: $('a').MyPluginMethod(); for each <a> tag that exists, it will add a <span> tag after it.

If we change it like this:

(function($){
$.fn.MyPluginMethod= function() {
    title= $(this).attr('title');
    alert(title);
};
})(jQuery);

It will not alert the title for each <a> tag that exists, only for the first occurence.

Why this behaviour? Thanks

Upvotes: 0

Views: 68

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

This is because you are creating 1 instance of the plugin, so the alert() is called once. The reason the first example results in span elements after every a is because the after() jQuery function loops through the matching set of elements.

To get your latter example to work as you want, you need to loop manually:

(function($){
    $.fn.MyPluginMethod= function() {
        this.each(function() {
            title = $(this).attr('title');
            alert(title);
        });
    };
})(jQuery);

You can check to see if the plugin has been instantiated on multiple elements by using this.length

Upvotes: 4

Rohan Kumar
Rohan Kumar

Reputation: 40639

It will alert when you call it, Also use $.each to call it for multiple elements like

HTML

<div title="test">test</div>
<div title="test123">test123</div>

SCRIPT

(function($){
$.fn.MyPluginMethod= function() {
    return $(this).each(function(){
      title= $(this).attr('title');
      alert(title);
    });
};
})(jQuery);
$('div').MyPluginMethod();

Updated Fiddle

Read http://learn.jquery.com/plugins/basic-plugin-creation/

Upvotes: 0

Related Questions