1

Can we create user defined function in jquery like :

    $(selector).click(function()
   {

    })

Above function is already in jquery library.

if i want to create function like above one For e.g. :

$(selector).demo();

How i can create function "demo()" to which i can prefix the selector as $(selector).demo();

2 Answers 2

2

by jQeury.fn.extend()

jQuery.fn.extend({
    demo: function(value){
       alert(value);
    }
});

you can also pass parameters if you need, like 10 in this example.

$(selector).demo(10);

if you would like to pass a function

$.fn.extend({
        demo: function(func){
            if(typeof func === 'function')
                func();
        });

pass the function then you trigger it in demo

  $(selector).demo(function(){
      alert('test');
  });

hope it will help you!

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this...Can i pass function as parameter to demo()?
sure! in javascript function is also a object, you can parse it definetely
I add some further information for you , take a look!
2

So:

jQuery.fn.newfunction= function() {

//code goes here

};

And then call:

$(element).newfunction();

jQuery.fn.extend()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.