Udders Udders - 4 months ago 12
Javascript Question

jquery plugin add event listener

I have a jquery plugin that I have created, that shows content and hides content in a tab like interface. What I am wanting to is trigger an event when some content is shown that I can then listen for in my source code, and fire an event based on that is that possible?

Here is my plugin,

$.fn.appsTabs = function(options){

// These are the defaults.
var settings = $.extend({
// These are the defaults.
selected: "home"
}, options );

// Set Active
$(this).find('.pops-tabs-navigation li[data-route="'+settings.selected+'"]').addClass('active');

// Hide All Boxes and show first one
$(this).find('.apps-tabs-content .pops-tab-content').addClass('cloak');
$(this).find('.pops-tabs-content .pops-tab-content#content-'+settings.selected).removeClass('cloak');
// Get Clicks on Li in Navigation
$(this).find('.apps-tabs-navigation li').click(function(){
if($(this).hasClass('active') == false) {
// Get ID of Tab
id = $(this).attr('id');
tabid = 'content-'+id;

// Set Active
$(this).parent('.apps-tabs-navigation').find('li').removeClass('active');
$(this).addClass('active');

// Hide all boxes
$(this).parent('.apps-tabs-navigation').parents('.pops-tabs').find('.pops-tabs-content .pops-tab-content').addClass('cloak');
$(this).parent('.apps-tabs-navigation').parents('.pops-tabs').find('.pops-tabs-content #'+tabid).removeClass('cloak');
}
});
}


Is it possible to maybe add something to the prototype and listen for that in my main application code?

Answer

In your plugin code, you can trigger a custom event and listen to it in the page javascript:

Plugin

// Show your element (example)
$('#myElement').show();
// Trigger custom event
$(document).trigger('myCustomPluginEvent');

Page

// Event listener for custom event 'myCustomPluginEvent'
$(document).on('myCustomPluginEvent', function() {
   // Do something when custom event occurs
});
Comments