So i assume this should be pretty simple… its just a custom Checkbox plugin that takes div’s and turns them into checkboxes using css. All i really need it to do is basically swap css and trigger events. I only see need for these actions (init, check, uncheck, toggle, disable).
Any way heres what i have so far, but im stuck on the toggle method and the last part in general…
(function ($) {
var method = {
init: function () {
$(this).addClass('cb-unchecked');
$(this).click(//Should call toggle method, but unsure syntax);
},
check: function () {
return this.each(function () {
$(this).removeClass('cb-disabled cb-unchecked').addClass('cb-checked').trigger('checked', this);
});
},
uncheck: function () {
return this.each(function () {
$(this).removeClass('cb-disabled cb-checked').addClass('cb-checked').trigger('unchecked', this);
});
},
toggle: function () {
return this.each(function () {
var t = $(this);
if (t.hasClass('cb-checked')) { //Should call the check function, but i dont know how... }
else if (t.hasClass('cb-unchecked')) { //Should call the uncheck function, but i dont know how...}
});
},
disable: function () {
return this.each(function () {
$(this).removeClass('cb-checked cb-unchecked').addClass('cb-disabled').trigger('disabled', this);
});
}
};
$.fn.customCheckbox = function (action) {
//Im slightly lost at what would go here
//if(method[action]){ method[action].apply(this, arguments); }//????
return this;
}
})(jQuery);
Am i headed in the right direction or should i be going about this completely differently?
Yes, you are on the right track. You wrapped it in (function($){..})(jQuery) to let jQuery play nicely with other javascript libraries. You maintain chainability by
return this;. You properly extend jQuery by using$.fn.customCheckbox = .... You can do as your comment says by applying the parameters to the function. Finally, just call it.although i would probably move the init code into the body of
$.fn.customCheckbox = function (action) {...}when!action