asprin asprin - 1 month ago 4x
jQuery Question

How to attach click event to an element inside my jQuery plugin?

I'm making a plugin and need to allow the end user to be able to take control of a click event being invoked from inside the plugin.

How would I go about achieving that? I've so far worked upto this point:

(function($) {
$.fn.multiForm = function(options) {
var settings = $.extend({
titles : [],
nextButton: 'nl-next',
prevButton: 'nl-prev',
onNext: function(){}
}, options);

//#1 I first need to attach a click event on settings.nextButton element
//#2 So when that button is clicked, I want the user to use oNext() and return true or false which I will then capture inside this plugin

this.each( function(options) {
// some plugin code

This is how the user will use the plugin:

// return either true or false
// I need to capture this return value


From within your plugin, you can call settings.onNext and use its return value.

if(typeof settings.onNext === 'function') {
   var result = settings.onNext();
   if(result) { ... }

You attach a click event to the nextButton like you would with any other button:

$(setting.nextButton).click(function() { 

Note that nl-next is not a valid jQuery selector. Is it a class name? If so, make sure to add . to the selector.

Also note that you may want to pass some context, to make sure that you don't add the listener to all buttons of this class, in case there are several instances of your plugin on the page.

$('.' + setting.nextButton, someDivWrappingMyPlugin).click(function() {