2

PREFACE
This did not help: enter image description here This did not help: https://www.w3schools.com/js/js_functions.asp

This did not help: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

Please do not ask/tell me to search the forum, I did. I also searched Google. I looked at every piece of documentation I could find and for (about three years) have not been able to understand this, (I'm sure) rather simple concept.

QUESTION
I understand the basic usage of function parameters such as this:

function myFunction(x) {
  var result = x * 2;
    console.log(result)
}
myFunction(4);

I have always understood that usage. The usage I do NOT understand is this:

$("a").click(function(event){
    event.preventDefault();
});

The variable seemingly comes out of nowhere. I understand that the variable is essentially declared/defined when you use it as a parameter, but what exactly is going on in that function? I know what the end result is, but how is it achieve by using "event". What is event?? What is its value??

Everything I have read on the web only ever explains the first usage of parameters, which is easy enough. Any help on the second usage, which I do understand they are actually being used the same way, would be greatly appreciated!

16
  • 4
    What don't you understand? "What is event?" - it's the parameter the function is called with, same as any other function. They're the same usage, there's nothing special happening here; you could do $("a").click(myFunction) then the event would be named x inside myFunction. Commented May 23, 2017 at 20:20
  • 4
    In this case the event parameter is this: api.jquery.com/Types/#Event as noted in the jquery click method docs: api.jquery.com/click Commented May 23, 2017 at 20:20
  • 2
    Can I recommend you take out your preface? It makes you sound belligerent preemptively. I realize you may be frustrated by the poor answers you've received in the past, but I think this will be a better post if you move that to an epilogue and make it sounds like...90% less angry. The screenshot is also sort of unnecessary, just tell us that you've searched for it before with no helpful results. Commented May 23, 2017 at 20:32
  • 2
    This being answered oustide of comments, but jquery is passing that parameter into your function, which you are passing into its click method. When your function gets called, that event object is created by jquery and is passed into your method as the first parameter. That parameter within your method could be named anything, basically whatever the first parameter of your function is, that will be the event object passed in from the jquery event occurrence. It only lives within the scope of your function, but could be assigned to a variable at a different scope if you'd like. Commented May 23, 2017 at 20:35
  • 1
    If you want to learn JS, you should learn the basics before you try to use jQuery. Here is the reference on events: developer.mozilla.org/en-US/docs/Web/API/EventTarget/… Commented May 23, 2017 at 20:55

4 Answers 4

7
$("a").click(function(event){
    event.preventDefault();
});

The parameter you are passing to the function click is, itself a function. It looks like this:

function(event){
        event.preventDefault();
}

So event is the parameter that will be passed to that function by whatever calls that function. What calls that function is jQuery, when a click event happens on the targeted element(s).

If you look at the documentation for click you'll see this:

.click( handler )

handler

Type: Function( Event eventObject ) A function to execute each time the event is triggered.

So your function that you are passing is handler. Handler is a function that takes an eventObject (which you called simply event, which is fine - it doesn't matter here) argument of the type Event

So simply put, you don't need to worry about how that function gets called. The library will call it at the appropriate time and pass the appropriate object as event to that function. All you need to worry about is what to do in that handler which may or may not involve actually using event.

It might be confusing you that the function you are passing to click is anonymous. It doesn't have a name. If it helps, you can do this:

 function MyClickHander(event) {
     // do something here
 }

 $("a").click(MyClickHandler);

Which is essentially the same. But people often prefer to use anonymous functions rather than write potentially dozens of named handler functions for all the various events they might need to worry about.

EDIT:

It might help to also think about how you might write a function that took a function as a parameter (e.g. a function that takes a callback):

function Foo(callback) {
    bar = someValue;
    callback(bar);
}

Which you might use like this:

Foo(function(bar) {
    console.log(bar);
});

So here bar comes from inside Foo - just like event comes from inside click. You don't have to worry about exactly where in click event comes from (although you can dig through the source code if you are really so inclined), the jQuery documentation tells you what click will do with your handler so you don't have to.

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

2 Comments

Thank you for your answer Matt. I know it might sounds stupid, but I understand that the anonymous function is a parameters of the click function. That part I get. What I don't get is "event". I understand it is a parameter of the anonymous function, but I didn't understand where it came from. What I missed (because my brain is fried from researching other stuff) is this line: "Required. The event parameter comes from the event binding function". So these parameters do not come out of nowhere as they appear to. That was my mistake. Thanks again.
The event object is created by the browser, and passed to the listener function when an event happens.
2

Functions are first class citizens in javascript. So you can pass them around and assign them to variables. Don't think of them as control structures, but as things themselves. In the case of your click listener, the argument you are passing actually IS the function. You are telling the jQuery library "here is a function I want you to call whenever a click happens." And the jQuery documentation promises that, at the time it calls your function, it will call it with an argument of event.

Maybe it helps you to see the code this way:

var callMeOnClick = function(event){
    console.log(event);
};//nothing has happened yet. The function is being assigned to a variable, not invoked.
$("a").click(callMeOnClick);//giving the function to jQuery to execute later.

I think I understand the question you are asking, I'm just not sure how to explain it best. I hope that helps somewhat though.

1 Comment

Thank you for your answer! To be honest, my brain is fried today so I am going to go back and review these answers tomorrow with a clear head. Thank you for breaking it down in a more understandable fashion though!
2

I typed up a long and technical definition of a callback function, but let me just leave you with this.

Whenever someone clicks on a, a spy is going to call your cell phone and give you detailed information about this click.

What are you going to do with that information?

  • The spy is jQuery
  • Your cell phone is your provided function declaration
  • Information about the click is event
  • What are you going to do with that information? It's whatever you write in the function body.

Comments

2

What you're showing as the 'second usage' is a really common form of a jQuery event function. You're asking us not to provide you documentation, but frankly you've been reading the wrong documentation.

The event 'variable' is actually an event object. I'll analyze examples below.


Here's something ripped straight from the documentation:

// Access the `dataTransfer` property from the `drop` event which
// holds the files dropped into the browser window.
var files = event.originalEvent.dataTransfer.files;

To address the specific usage that you posted, i.e. preventDefault(), here's the documentation on it, and another example:

Description: If this method is called, the default action of the event will not be triggered... For example, clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

Example: Cancel the default action (navigation) of the click.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>event.preventDefault demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>
  <a href="https://jquery.com">default click action is prevented</a>
  <div id="log"></div>
  
  <script>
    $( "a" ).click(function( event ) {
      event.preventDefault();
    $( "<div>" )
      .append( "default " + event.type + " prevented" )
      .appendTo( "#log" );
    });
  </script>
</body>
</html>

Assuming you haven't given up completely on trying to learn for yourself, here's a good link that will explain the implementation: https://api.jquery.com/category/events/event-object

2 Comments

First, thank you for your answer. Second, I did not say not to post documentation, I said "Please do not ask/tell me to search the forum". I am completely opening to learning this on my own, the problem is that I have been unable to do so up to this point. Anyway, thank you for your answer.
I apologize if I came across as rude, but your original question gave me the wrong impression. I'll happily edit it for tone, if you'd like! I hope my answer was helpful, although I admit that better answers have been posted above.

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.