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.
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.
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.
jQuery click() Method The click() method triggers the click event, or attaches a function to run when a click event occurs.
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.
You should do two things:
this
to reference the elements to which your plugin is being appliedTry 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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With