Reputation: 612
I am trying to create a little jquery plugin, but the problem I get is that if I call it a few times for a few different divs, the last call overrules all others and I get that last result on each div.
<div class="p1"><p>text 1</p></div>
<div class="p2"><p>text 2</p></div>
<div class="p3"><p>text 3</p></div>
JS:
var changeColor = {
init: function(options, elem) {
var self = this;
self.elem = elem;
self.options = $.extend( {}, $.fn.changeColor.options, options );
self.blueColor();
},
blueColor: function() {
var self = this;
$('p').css('color', self.options.color);
}
};
$.fn.changeColor = function( options ) {
return this.each(function() {
var color = Object.create( changeColor );
color.init( options, this );
$.data( this, 'changeColor', color );
});
};
$.fn.changeColor.options = {
color: 'green'
};
(function() {
$('.p1').changeColor({color: 'yellow'});
$('.p2').changeColor({color: 'blue'});
})();
Now both <p>
in both divs will be blue, instead of the first one being yellow and the second blue.
Upvotes: 3
Views: 106
Reputation: 5106
You are applying the color style to all <p>
elements when you do $('p')
. Apply the changes only to the selected element by using $(self.elem)
.
Change this
$('p').css('color', self.options.color);
For this
$(self.elem).css('color', self.options.color);
You can see a fiddle here, this portion of the code is at line 16.
EDIT: As very well pointed out by skafandri this changes the <div>
color, not <p>
's. To change the color of the paragraph change your selector:
$('.p1 p').changeColor({color: 'yellow'});
$('.p2 p').changeColor({color: 'blue'});
Upvotes: 2