Detect if jQuery plugin is applied to multiple elements?

I am working on a jQuery plugin that can be applied to multiple elements. The plugin includes some animation effects, and I need to manage the event queue based on whether the plugin is used for several elements (instead of one).

What is the best way to determine if a plugin has been applied to a single item or to multiple items?

Edit ...

Property lengthworks correctly if the plugin transferred several elements (e.g., $('.myClass').plugin()), but if the plug is caused to several individual elements (such as $('#myElem1').plugin()and $('#myElem2').plugin()), then the length returned by one for each call.

Is there a way to detect multiple instances when the plugin is used, as in the second example /

+3
source share
3 answers

thisinside the plugin, depending on your style, refers to a jQuery object, so you can just check the property.length , for example:

 jQuery.fn.plugin = function(options) {
   if(this.length > 1) //being applied to multiple elements
 };

For your editing: tracking the total may be the best option, for example:

(function($) {
  $.pluginCount = 0;
  $.fn.plugin = function(options) {
    $.pluginCount += this.length;    //add to total
    if($.pluginCount > 1) //overall being applied to multiple elements
  };
})(jQuery)
+5
source

Suppose you have applied your plugin for $ ('some selector'). myPlugin (), the keyword "this" will refer to the jquery object that you called the plugin inside your plugin function.

So, we summarize:

(function ($) {
  $ .fn.myPlugin = function () {
    if (this.size ()> 1) {
       // code for multiple elements
    }
    else if(this.size() == 1) {
       //code for 1 element
    }
  }
})( jQuery );

$('div.to-pluginize').myPlugin();
+1

If you need a general way to check if a plugin has been applied to an arbitrary set of elements, here is one approach:

// say we want to apply this to a bunch of elements
​​$.fn.test = function(str) {
    this.each(function() {
        // set a boolean data property for each element to which the plugin is applied
        $(this).data('test', true);
        alert(str);
    });
};


// use a simple plugin to extract the count of a specified plugin
// from a set of elements
$.fn.pluginApplied = function(pluginName) {
    var count = 0;
    this.each(function() {
        if($(this).data(pluginName)) {
            count++;
        }
    });
    return count;
};

with this markup:

<a href="test" class="test">Hello</a>
<br />
<a href="test" class="test">Hello</a>

Here is the test:

$("a").test('test');

alert($("*").pluginApplied('test'));​​​​​​​​​​​​​​​​ // alerts '2'

Demo: http://jsfiddle.net/B5QVC/

+1
source

Source: https://habr.com/ru/post/1765992/


All Articles