Calling a user defined function in jQuery
Asked Answered
H

11

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?

Hl answered 25/3, 2010 at 23:27 Comment(2)
I would define this as a pluginMisbecome
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/H7z8fPiscine
T
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>
Titmouse answered 26/3, 2010 at 0:29 Comment(4)
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 }});Piscine
@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... thanksZolly
This didnt work for me. The one by Ruslan López Carro worked (its below.)Beseem
@NickCraver if myFunction take parameter how do you pass parameter to function myFunction during its call? ThanksRichman
S
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>
Satyriasis answered 7/12, 2010 at 12:30 Comment(1)
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 apiChancre
C
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();
Corin answered 26/3, 2010 at 0:3 Comment(0)
R
10

The following is the right method

$(document).ready(function() {
    $('#btnSun').click(function(){
        $(this).myFunction();
     });
     $.fn.myFunction = function() { 
        alert('hi'); 
     }
});
Rojo answered 11/1, 2012 at 6:20 Comment(0)
S
8

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

This should work

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

function myFunction()
{
alert('hi');
}
Sessoms answered 25/3, 2010 at 23:30 Comment(4)
So is it mean that we can't create user defined function in Jquery and call as we normally do?Hl
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?Hl
You are assinging it to the jQuery object.Sessoms
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 (){}?Swaney
S
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.
Squeeze answered 29/3, 2010 at 9:35 Comment(0)
N
2
$(document).ready(function() {
  $('#btnSun').click(function(){

      myFunction();

   });

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

    }; 
});

Put ' ; ' after function definition...

Numerate answered 15/7, 2013 at 14:43 Comment(0)
A
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.

Anikaanil answered 29/8, 2012 at 12:20 Comment(0)
N
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">
Nataline answered 8/4, 2018 at 3:48 Comment(0)
V
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();
Varion answered 18/3, 2019 at 9:41 Comment(0)
R
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.

Radial answered 28/1, 2020 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.