-1

I am wondering if anyone can help with understanding this Javascript syntax.

Lets say I have the following:

<script>
    $(function(){
        $("#contactbutton").click(function(event){
            $("#dialog").dialog({width:500});
        });
    });
</script>

I understand that the first line is testing if the DOM is ready and loaded. It then passes control to the inside function.

This inside function gets the element with an ID of contactbutton and for the click event, passes control to the next function.

This inner function, gets the elemnt with an ID of dialog and calls the .dialog method to display the dialog box. However, I am not sure about:

function(event)

What is the event parameter here, and why do we need it? Also, can this be renamed to anything we want?

Thanks,

4
  • 1
    Yes it can be renamed or removed. But you might want to have access to the event to see, e.g., the coordinates at which the mouseclick happened. That info is part of the event object. Commented Jan 4, 2015 at 19:08
  • The event argument is a built in argument, you don't seem to need it so you can just remove it Commented Jan 4, 2015 at 19:08
  • @charlietfl in fact there are more arguments available , second argument is element Can you explain what do you mean? Commented Jan 4, 2015 at 19:41
  • @A.Wolff what he means that in certain contexts, the element is also accessible by passing it through to the event handler. For example, the jquery each function can be passed two parameters, one is the index the other is the respecitve element: api.jquery.com/each Commented Jan 5, 2015 at 10:08

1 Answer 1

2

This is actually an object that is accessible within that function. Usually it is called the event reference. The object holds details, functions, variables, etc., about the function and event, allowing you to handle the event and access properties of it. You are able to access it once you set a name to the first argument of the handler, that is function(event) { }

In a certain case, say you wanted to prevent the default event of an anchor link which would be to navigate the page to stackoverflow.com. preventDefault is a function that can do this, that is, prevent the default event. In this case that would be to prevent the navigation to stackoverflow.com. You are able to access the preventDefault function using the syntax event.preventDefault() if you have assigned the name event to the first argument of the handler.

For another example, in an onkeydown event you can access which key has been pressed with event.keyCode.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.