65

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user269867
  • 3,266
  • 9
  • 45
  • 65
  • 1
    I would define this as a **plugin** – Jacob Relkin Mar 25 '10 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()`. http://jsfiddle.net/H7z8f/ – Junior Mayhé Sep 23 '12 at 14:32

11 Answers11

87

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>
Ruslan López
  • 4,433
  • 2
  • 26
  • 37
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    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 }});` – Junior Mayhé Sep 23 '12 at 14:15
  • 4
    @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 – Amjad Jun 18 '14 at 16:06
  • This didnt work for me. The one by Ruslan López Carro worked (its below.) – alikuli Oct 24 '15 at 02:50
  • @NickCraver if `myFunction` take parameter how do you pass parameter to function `myFunction` during its call? Thanks – Houy Narun Oct 12 '18 at 05:12
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>
Ruslan López
  • 4,433
  • 2
  • 26
  • 37
neeraj
  • 391
  • 3
  • 2
  • 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**](http://stackoverflow.com/a/34625042/5737774) – fWd82 Feb 08 '17 at 12:07
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();
jholster
  • 5,066
  • 1
  • 27
  • 20
10

The following is the right method

$(document).ready(function() {
    $('#btnSun').click(function(){
        $(this).myFunction();
     });
     $.fn.myFunction = function() { 
        alert('hi'); 
     }
});
sjngm
  • 12,423
  • 14
  • 84
  • 114
CreativeMirage
  • 101
  • 1
  • 2
8

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

This should work

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

function myFunction()
{
alert('hi');
}
genesis
  • 50,477
  • 20
  • 96
  • 125
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • So is it mean that we can't create user defined function in Jquery and call as we normally do? – user269867 Mar 25 '10 at 23:35
  • 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? – user269867 Mar 25 '10 at 23:39
  • You are assinging it to the jQuery object. – Daniel A. White Mar 25 '10 at 23:45
  • 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 (){}`? – bcherry Mar 25 '10 at 23:49
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.
genesis
  • 50,477
  • 20
  • 96
  • 125
dbrainer
  • 51
  • 1
2
$(document).ready(function() {
  $('#btnSun').click(function(){

      myFunction();

   });

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

    }; 
});

Put ' ; ' after function definition...

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.

Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Kamalpreet
  • 11
  • 1
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">
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();
Deepak A
  • 1,624
  • 1
  • 7
  • 16
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.

Harry Moreno
  • 10,231
  • 7
  • 64
  • 116