-2
$("p").click(function(){
  // action goes here!!
});

In the above jquery code why we pass a function() to the event?

Haris N I
  • 6,474
  • 6
  • 29
  • 35
  • 1
    simply what you want to do when you click? you can do .click(alert('clicked')) too. – Bhojendra Rauniyar Jul 03 '15 at 04:59
  • 1
    @BhojendraNepal No, you *can't* do that with successful result. The entire point of a ***callback* function** is that is executed in a deferred manner. Directly calling the alert (or any function that does not return a suitable callback) will not be result in a deferred action; only the immediate side-effects. – user2864740 Jul 03 '15 at 05:08
  • also http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o?lq=1 – user2864740 Jul 03 '15 at 05:11

3 Answers3

0

Because the click method is defined this way (the method parameter ).
See: click

You have to understand its not a default JavaScript method, this method is defined in the JQuery so you have to call it as it is defined in the method.

Behind the scene actually when JQuery registering any event with DOM its only says to do one thing which is calling your provide method.

Saif
  • 6,804
  • 8
  • 40
  • 61
0

The simplest answer: according to documentation.
https://api.jquery.com/click/

When a user clicks a p element, jQuery is supposed to fire an event and execute something. How is it supposed to pass actions, if not using functions?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
0

It's called a callback or an anonymous function that you want executed when the event happens. You'll notice it's not just jQuery, but almost all Javascript frameworks will expect one. It's usually whenever you are binding to events, executing functions that might take a while to return, or functions that execute other functions.

But you can also provide it a function name if you want.

function clickedMe(){
   alert("Something clicked me");
}
$("p").click(clickedMe)
Marek
  • 320
  • 2
  • 5