66

I am trying to call a user defined function in jQuery:

$(document).ready(function() {
  $('#btnSun').click(function() {
    myFunction();
  });
  $.fn.myFunction = function() {
    alert('hi');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

I tried the following as well:

$(document).ready(function() {
  $('#btnSun').click(function() {
    myFunction();
  });
});

function myFunction() {
  alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

It doesn't seem to work! Any idea where I am wrong?

2
  • 1
    I would define this as a plugin Commented Mar 25, 2010 at 23:33
  • 1
    just a remark, since you are using $.fn.myFunction, in most cases you are telling that you want to use this function over a valid wrapped jquery object, eg. $('your_html_tag').myFunction(). jsfiddle.net/H7z8f Commented Sep 23, 2012 at 14:32

11 Answers 11

89

If you want to call a normal function via a jQuery event, you can do it like this:

$(document).ready(function() {
  $('#btnSun').click(myFunction);
});

function myFunction() {
  alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

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

4 Comments

If you need a custom function for an object (eg. a variable), you can use Object.prototype.SayIt = function(s){return this+s;}; var ramone='Hey Ho, '; var s = 'Lets go'; console.log(ramone.SayIt(s));​. If you have trouble, use Object.defineProperty(Object.prototype, "SayIt", {value: function (s) { your stuff here }});
@Nick Craver can you add parameters to user define function if so how would you use it {function myFunction(val1, val2) { //how would you use it here }} and how would you call the function... thanks
This didnt work for me. The one by Ruslan López Carro worked (its below.)
@NickCraver if myFunction take parameter how do you pass parameter to function myFunction during its call? Thanks
39

Just try this. It always works.

$(document).ready(function() {
  $('#btnSun').click(function() {
    $.fn.myFunction();
  });
  $.fn.myFunction = function() {
    alert('hi');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

1 Comment

I was trying to waste my time in some stupid thing. I tried every code which is mention here but was unable to even alert(0); it. Was trying to figure out solution and here it was, I pressed F12 and it seems my AdBlocker was blocking some contents from showing up. Read more: Failed to load resource in chrome google.maps api
12

They are called plugins, as Jaboc commented. To make sense, plugin function should do something with the element it is called through. Consider the following:

jQuery.fn.make_me_red = function() {
    return this.each(function() {
        this.style.color = 'red';
    });
};

$('a').make_me_red();

Comments

10

The following is the right method

$(document).ready(function() {
    $('#btnSun').click(function(){
        $(this).myFunction();
     });
     $.fn.myFunction = function() { 
        alert('hi'); 
     }
});

Comments

8

Try this $('div').myFunction();

This should work

$(document).ready(function() {
 $('#btnSun').click(function(){
  myFunction();
 });

function myFunction()
{
alert('hi');
}

4 Comments

So is it mean that we can't create user defined function in Jquery and call as we normally do?
Hey it works for me $('div').myFunction(); :-). Gr8 !! Can you help me to understand this behavior ?? why we need $('div').myFunction()... why can't I call myFunction as normal function?
You are assinging it to the jQuery object.
because myFunction is not a normal function, it's a property of the jQuery object's prototype, which is why you can call $('div').myFunction(). If you want to just be able to call myFunction, then why not just make a function myFunction (){}?
5
jQuery.fn.make_me_red = function() {
    return this.each(function() {
        this.style.color = 'red';
    });
};

$('a').make_me_red() // - instead of this you can use $(this).make_me_red() instead for better readability.

Comments

2
$(document).ready(function() {
  $('#btnSun').click(function(){

      myFunction();

   });

   $.fn.myFunction = function() { 
     alert('hi'); 

    }; 
});

Put ' ; ' after function definition...

Comments

1
jQuery.fn.make_me_red = function() {
    alert($(this).attr('id'));
    $(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
    //$(this).siblings(".hello").make_me_red(); 
    $(this).make_me_red(); 
    $(this).addClass("active");
});
​

Function declaration and callback in jQuery.

Comments

0

function hello(){
    console.log("hello")
}
$('#event-on-keyup').keyup(function(){
    hello()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="event-on-keyup">

Comments

0
jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 


$('#my-form').clear();

Comments

0

in my case I did

function myFunc() {
  console.log('myFunc', $(this));
}
$("selector").on("click", "selector", function(e) {
  e.preventDefault();
  myFunc.call(this);
});

properly calls myFunc with the correct this.

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.