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.myPlugin.js
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);
});
};
HTML
<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>
The
extendfunction 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: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
extendat all, and just do something like this: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 passthisintojQuerysince it is already an instance ofjQuery.Here’s a working example of that one.