Reputation: 6894
I have written a small plugin to change the text size but it doesn't seem to work properly. $('#mypara').changeTextSize('30px'); doesn't set the size to 30px but instead sets to 10px
jQuery.fn.changeTextSize = function(size){
alert(size); //shows 30px
var config = {
'size' : '10px'
};
if(size) {
$.extend(config,size);
}
alert(config.size); //shows 10px
return $(this).each(function() {
$(this).css('font-size',config.size);
});
};
<script type = "text/javascript" src="jquery-1.7.1.js"></script>
<script type = "text/javascript" src="jquery.myPlugin.js"></script>
<script>
$(document).ready(function() {
$('#mypara').changeTextSize('30px');
});
</script>
</head>
<body>
<p id="mypara">dsfdsfdsf</p>
</body>
Upvotes: 0
Views: 367
Reputation: 165961
The extend
function is used to merge objects. You are trying to merge a string, size
, into an object literal, config
. You would need to pass an object as the argument to your plugin:
$('#mypara').changeTextSize({
size: '30px'
});
Here's a working example.
Alternatively, if that's the only argument and there's not going to be more options, it may be easier to forget about using extend
at all, and just do something like this:
jQuery.fn.changeTextSize = function(size){
return this.css('font-size', size || "10px");
};
Notice how I've removed the each
, since there is no need for it (most jQuery methods apply to every element in the matched set by default), and you also don't need to pass this
into jQuery
since it is already an instance of jQuery
.
Here's a working example of that one.
Upvotes: 3