Hello,
today I decided to look into jquery plugins, and with the help of various tutorials I have produce a very simple one that changes the colour of some elements in a page. I would appreciate some help in understanding whether there is something else that I need to do to make it bullet proof (I am sure this plug in in itself is completely useless but it was a good exercise for me to understand how the whole plugin world works).
So here is the HTML first:
<div class="divContainer">
<p>Changing colour plugin</p>
<div class="square">Square 1</div>
<div class="square">Square 2</div>
<div class="square">Square 3</div>
<div class="square">Square 4</div>
<div class="square">Square 5</div>
<div class="square">Square 6</div>
<div class="square">Square 7</div>
<div class="square">Square 8</div>
<button class="changeColour">change colour</button>
</div>
Then the CSS:
.divContainer{
width:600px;
height:300px;
background-color:grey;
position:absolute;
top:450px;
}
.square{
background-color:red;
width:50px;
height:50px;
margin-right:10px;
float:left;
}
And the script:
$(".changeColour").click(function(){
$(".square").colourThem({
background: 'yellow',
color: 'red'
});
});
/*plugin with options*/
(function($){
$.fn.colourThem = function( options ){
//declare defaults
var defaults = {
background:'green',
color:'white'
}
var settings = $.extend({}, defaults, options );//new object merging defaults and options
this.css({ "backgroundColor": settings.background,
"color": settings.color
});
return this;
}
}(jQuery));
So, in one of the tutorials (this one is brilliant by the way http://net.tutsplus.com/articles/news/you-still-cant-create-a-jquery-plugin/) I have read that when we build plug-ins since we return an object that contains many elements we need to cycle through them with this.each(function() { }
.
In my case I have added that to have this
(function($){
$.fn.colourThem = function( options ){
//declare defaults
var defaults = {
background:'green',
color:'white'
}
var settings = $.extend({}, defaults, options );
this.each(function() {
this.css({ "backgroundColor": settings.background,
"color": settings.color
});
}
return this;
}
}(jQuery));
but this breaks my plug-in. What have I done wrong?
thanks