Udders Udders - 1 year ago 187
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

// 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 Source

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


// Show your element (example)
// Trigger custom event


// Event listener for custom event 'myCustomPluginEvent'
$(document).on('myCustomPluginEvent', function() {
   // Do something when custom event occurs
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download