views:

1176

answers:

4

Hi,

I am trying to call user defined function in jquery.

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

I tried following as well

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

but it doesn't seems to work !! Any idea where I am wrong?

Regards, Priti

A: 

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

This should work

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

function myFunction()
{
alert('hi');
}
 });
Daniel A. White
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.
Daniel A. White
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
Thanks Daniel and bcherry :-)
A: 

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
A: 

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');
}
Nick Craver
A: 

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.

dbrainer