I have this little jQuery plugin:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
(function($){
$.fn.foo = function(options){
var options = $.extend({
text: "Foo!",
}, options
);
this.prepend(
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
return this;
};
})(jQuery);
$(function(){
$("div").foo().foo({text: "Bar!"}).css({border: "1px solid red"});
});
//--></script>
</head>
<body>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
Now I want to improve it so you are able to control where the text gets inserted by means of providing a callback function:
$(function(){
var optionsFoo = {
text: "Foo!",
insertionCallback: $.append
}
var optionsBar = {
text: "Bar!",
insertionCallback: $.prepend
}
$("div").foo(optionsFoo).foo(optionsBar).css({border: "1px solid red"});
});
(Please remember this is just sample code. I want to learn a technique rather than fix an issue.)
Can I pass a jQuery method as an argument and use it inside the plugin in the middle of a chain? If so, what's the syntax? If not, what's the recommended alternative?
Update: myprogress so far
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
(function($){
$.fn.foo = function(options){
var options = $.extend({
text: "Foo!",
insertionCallback: $.append
}, options
);
options.insertionCallback.call(this, // options.insertionCallback is undefined
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
return this;
};
})(jQuery);
$(function(){
var optionsFoo = {
text: "Foo!",
insertionCallback: $.append
}
var optionsBar = {
text: "Bar!",
insertionCallback: $.prepend
}
$("div").foo(optionsFoo).foo(optionsBar).css({border: "1px solid red"});
});
//--></script>
</head>
<body>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>