TGH
TGH

Reputation: 39248

Multiple JQuery plugins on same page

I am wondering if there is an easy solution to this: I have the following JQuery plugin created several times on elements defined in a grid

(function ($) {
    $.fn.MyPlugin = function () {

        $(this).mouseenter(function () {
           //do something for single plugin instance
        });
    };

})(jQuery);

However, how can I go about uniquely identfying which plugin instance I am triggering the mouse enter function on. With the current setup I am referencing all the instances, but I want to only trigger the mouseenter for one of them at the time.

The plugin is created like this:

$(".someClass").MyPlugin(); 

Upvotes: 0

Views: 511

Answers (2)

elclanrs
elclanrs

Reputation: 94101

You don't need to create a plugin mutiple times, that's why it's called a plugin. You just plug it in wherever you want. Take a look at the jquery plugins authoring page on how to start coding a plugin. It provides some nice templates.

In your code $(this) is redundant, since this is already a jQuery object. Then, you'd want to always return this to maintain chainability in your plugin. You can use $(this) inside the mousenter event to reference the current element being processed by the plugin in the DOM.

Sometimes it's also useful to return this.each() and loop each element and do something. In this case, since you're attaching an event it doesn't help because an event works on every item in the collection of items; in this case, this refers to the collection on which you called the plugin:

$.fn.MyPlugin = function () {

    return this.mouseenter(function () {
       $(this).something();
       //do something for single plugin instance
    });

};

Then you'd call the plugin like so:

$('elements').MyPlugin();

Just call the plugin on the element(s) that you want and those elements will have the mouseenter event attached.

Upvotes: 2

Brian
Brian

Reputation: 2229

what is the html where you are using the plugin? mouseenter can be connected to an element id so instead of calling (this).mouseenter, call the div by id (i.e $("div.somediv").mouseenter(function(){ .... what you want to do ..... }

the jquery site shows an example of using multiple mouse events for nested divs.

http://api.jquery.com/mouseenter/

Upvotes: 1

Related Questions