Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle click events inside a jQuery plugin?

How do you handle click events inside a plugin? A simplified description is that I want to have a plugin that will detect a click and then update another element.

Example Usage:

$("#some_id").myPlugin("another_id");

Example Plugin:

(function($){

     $.fn.myPlugin=function(update_id){

     .click({$(update_id).html("content_upated");});

     }

})(jQuery);

I don't understand how to code the .click event inside the plugin. Any examples would be helpful. Thanks.

like image 425
DLL Avatar asked Sep 07 '11 17:09

DLL


People also ask

How is an event handled in jQuery?

A jQuery Event is the result of an action that can be detected by jQuery (JavaScript). When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions are called Event Handlers.

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

Which jQuery function is used to call a function on click event?

jQuery click() Method The click() method triggers the click event, or attaches a function to run when a click event occurs.

How click event works in JavaScript?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.


2 Answers

You should do two things:

  1. Use this to reference the elements to which your plugin is being applied
  2. Namespace your events, so they can easily be unbound later

Try the following

(function($){

     $.fn.myPlugin = function(update_id) {

       this.bind("click.myPlugin", function () {
         $(update_id).html("content_upated");
       });

    };

})(jQuery);

You should read the page on jQuery plugin authoring for more information on how to correctly develop jQuery plugins. You're missing other important details like accepting an arguments object.

like image 70
meagar Avatar answered Sep 24 '22 23:09

meagar


Use this to access the object that the plugin is being invoked on:

(function($){
     $.fn.myPlugin=function(update_id){
         this.click( function() { $(update_id).html("content_upated"); } );
     }
})(jQuery);

Note that your usage would need to include the id selector in this example, or you would need to include it in your click function:

$("#some_id").myPlugin("#another_id");
like image 24
Kasaku Avatar answered Sep 23 '22 23:09

Kasaku