Beginnerprogrammer Beginnerprogrammer - 12 days ago 5
Javascript Question

How to define a jQuery function properly

I want to write an jquery function because otherwise I have to write some code over and over.

Here is wat the function was first:

$(".checkbox-car").click(function(){
$(this).toggleClass('checked-car')
});

$(".checkbox-bus").click(function(){
$(this).toggleClass('checked-bus')
});


And this is what I tried to do with my own function:

$.fn.checkedFunction = function(Clicked, Checked){
$(this).click(function(){
console.log('check');
$(Clicked).toggleClass(Checked);
});
}

$('.checkbox-car').checkedFunction('.checkbox-car','.checked-car');


But I get the error that the checkedFunction is not defined.

What am I doing wrong here can someone help me out?

Answer

You're getting an error that checkedFunction isn't defined because it isn't. checkedFunction is a property defined in$.fn object.

To use the function you created, you should do $(".some-element").checkedFunction(...args).

More over, you should read the jQuery docs.