Reputation: 4074
I created a re-usable plugin for a system I'm building. All seems to work fine as long as I only have 1 element on the page. If I have 2, the links and panels hide for both on a single click. How do I scope the plugin to work independently on each?
Thanks in advance.
The plugin is for tab creation and goes like this:
(function($){
$.fn.wbTabs = function() {
return this.each(function(){
// caching selectors
$this = $(this);
$tabLinks = $this.find('.tabs li a');
$firstTab = $this.find('.tabs li:first a');
$panels = $this.find('.panel');
// function on tab click
$tabLinks.click(function() {
$panels.hide();
$tabLinks.removeClass('active');
$(this).addClass('active').blur();
var panel = $(this).attr('href');
$(panel).show();
// prevent link from clicking
return false;
});
// make first tab active
$firstTab.click();
});
};
})(jQuery);
Then I call the plugin with this:
$('.wb-tabs-container').wbTabs();
Upvotes: 0
Views: 1345
Reputation: 18078
The jQuery Plugins/Authoring guidelines advise that "using jQuery's data method is a great way to keep track of variables on a per element basis." This is exactly what you need.
There are other approaches, chiefly exploiting closures but the data method is more intuitive.
Suggest you adopt the recommended plugin pattern with particular attention to section 6.3 Data. It's quite easy.
Upvotes: 0
Reputation: 966
Declare your variables, var, inside your plugin and you'll be good. You're setting global vars which ends up breaking your plugin (and will fail in some browsers anyway). fiddle: http://jsfiddle.net/brentmn/uJbxz/3/
var $this = $(this);
var $tabLinks = $this.find('.tabs li a');
var $firstTab = $this.find('.tabs li:first a');
var $panels = $this.find('.panel');
Upvotes: 1
Reputation: 5774
I would possibly try a different selector approach:
$this = $(this);
$tabLinks = $('.tabs li a', $this);
$firstTab = $('.tabs li:first a', $this);
$panels = $('.panel', $this);
This is also a much quicker process for the browser.
Upvotes: 0