Let's say - On any <UL> element in page, I want to define a few behaviours. Such as...
- If you click on any
<li>inside the<ul>, then its colour changes... - If you double-click an
<li>, then a new<li>gets appended at the end.. - and many other such behaviours ...
Now I know little jQuery using which I can write individual functions to accomplish these things....
$("ul li").on ('click', function () { ... .css() .. });$("ul li").on ('dblclick', function () { ... .append("<li>New Born Li</li>") ... });
But what I really want to do is to encapsulate all these functions in a single object (class) like structure. Then I will just associate that function on any element to enable those functionalities on that element. Something like this -
$("ul").enableMySpecialULFeatures ({
color: 'red',
textToAppend: 'New Born Li' ,
...
});
Once I call this function on <ul> then all the behaviours get applied on <ul>.
My Question is - how do I create this enableMySpecialULFeatures type of object function? Wondering if anyone can give me a boilerplate to get me started...
2 Answers 2
create js plugin like this:-
$.fn.enableMySpecialULFeatures = function(options) {
var settings = $.extend({
color: "#556b2f",
textToAppend: 'New Born Li'
}, options );
return this.each(function() {
$(this).find('li').click(function(){
$(this).css('color',settings.color);
});
$(this).find('li').dblclick(function(e){
e.preventDefault();
$(this).append('<li>'+settings.textToAppend+'</li>');
});
});
};
and use:-
$(function(){
$('ul').enableMySpecialULFeatures({
color:'green',
textToAppend:"hello"
});
});
3 Comments
$(function(){ }); is a shortcut for jQuery's $(document).ready() right?$(document).ready() instread if you wantAnd then improve @mohit-arora's example by using multiple event handlers on a single reference to $(this) in the return statement:
$.fn.enableMySpecialULFeatures = function(options) {
var settings = $.extend({
color: "#556b2f",
textToAppend: 'New Born Li'
}, options );
return this.each(function() {
$(this).find('li').on({
click: function(){
$(this).css('color',settings.color);
},
dblclick: function(e) {
e.preventDefault();
$(this).append('<li>'+settings.textToAppend+'</li>');
}
});
});
};
$.fnnow.. But how do I put the other behavioural functions (such as color changing and appending etc.) inside my new function?