This is my first stab at trying to create a JQuery plugin, so I apologize for my noobbery. My issue is that I believe the plugin is re-initializing when I try to call a public method. It’s a simple plugin that creates a div and fills it with tiles, the method .reveal() should remove the tiles.
Plugin declaration:
(function($){
$.fn.extend({
//pass the options variable to the function
boxAnimate: function(options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
bgColor: '#000000',
padding: 20,
height: $(this).height(),
width: $(this).width(),
tileRows:25,
tileHeight:$(this).height()/25,
tileCols:25,
tileWidth:$(this).width()/25,
speed: 500
}
var options = $.extend(defaults, options);
this.reveal = function(){
var lastTile = $('.backDropTile:last').attr('id');
var pos1 = lastTile.indexOf("_");
var pos2 = lastTile.lastIndexOf("_");
var lCol = parseInt(lastTile.substr(pos2+1));
var lRow = parseInt(lastTile.substr(pos1+1,(pos2-pos1)-1));
alert(lCol+' '+lRow+' #bdTile_'+lRow+'_'+lCol);
for(lRow;lRow>=0;lRow--){
//Iterate by col:
for(lCol;lCol>=0;lCol--){
$('#bdTile_'+lRow+'_'+lCol).animate({
opacity: 0
}, 100, function() {
$('#bdTile_'+lRow+'_'+lCol).remove();
});
}
}
alert(lCol+' '+lRow);
}
return this.each(function(index) {
var o = options;
//Create background:
$(this).prepend('<div id="backDrop" style="color:white;position:absolute;z-index:998;background-color:'+o.bgColor+';height:'+o.height+'px;width:'+o.width+'px;"></div>');
//create boxes:
//First iterate by row:
for(var iRow=0;iRow<o.tileRows;iRow++){
//Iterate by col:
for(var iCol=0;iCol<o.tileCols;iCol++){
$('#backDrop').append('<span class="backDropTile" id="bdTile_'+iRow+'_'+iCol+'" style="z-index:998;float:left;background-color:green;height:'+o.tileHeight+'px;width:'+o.tileWidth+'px;"></span>');
}
}
});
}
});
})(jQuery);
Usage:
$(document).ready(function() {
$('#book').boxAnimate();
$('#clickme').click(function() {
$('#book').boxAnimate().reveal();
});
});
So I pretty much know what my problem is, but I’m not familiar enough with creating jQuery plugins to fix it. It’s seems like the more I read, the more confused I become as it appears to be many ways to achieve this.
When you assign a method inside the plugin “constructor” like you do here:
you are assigning it as a static method of the
jQuery.prototype.boxAnimateobject. That means you can call it on the object that will be returned from the constructor:or:
If you wish to place it inside the
$.dataobject instead (personally recommended), you can do like this instead (inside the this.each loop):Example: http://jsfiddle.net/AyffZ/