2

I am learning jQuery at the moment and have managed to get the below function to work for attaching a keyboard click of 'enter' to a button. Although I can't work out why I need to put anything in the function parameter or at the beginning of the if statement.

For example, why does this work:

$('#enter').keypress(function(event) {
        if(event.keyCode == 13) {
            $('button').click();
        };
    });

And this doesn't:

$('#enter').keypress(function() {
        if(keyCode == 13) {
            $('button').click();
        };
    });

Here's the HTML:

<input id="enter" placeholder="Enter text"></input>
<button>Get Info</button>

I am struggling to understand the significance of 'event' here.

1 Answers1

0

In the first example, you are passing the event object to the function. When the event is triggered, keyCode is a property on the associated event object. If you don't pass the event object, you can't access the keyCode property, which is why your second example wasn't working.


As a side note, input elements don't have closing tags.

Change:

<input id="enter" placeholder="Enter text"></input>

to:

<input id="enter" placeholder="Enter text" />
Josh Crozier
  • 202,159
  • 50
  • 343
  • 273
  • Thanks for this, I think what is confusing me is that I can substitute anything for 'event' and it still works, for example, I could change the two occurrences of 'event' to 'apples' and it would still work. Also, thanks for the heads up on the HTML :) –  Dec 12 '15 at 04:36
  • @Wub That's because you can name the parameter whatever you want (since you are passing it). It can be passed as `e`, `event`, etc.. and it will still be the same `event` object because that is the first parameter that is passed to the function when the event is triggered. – Josh Crozier Dec 12 '15 at 04:39
  • Also, in regards to your point about the HTML, should this be written without the trailing slash because I am using HTML5? –  Dec 12 '15 at 04:52
  • @Wub It's up to you. It is completely valid on 'void' element (such as `input`/`img` elements) and it will [validate in HTML5](http://stackoverflow.com/a/3558200/2680216) with or without the trailing slash. It's just a personal preference. You will see the slash omitted sometimes. http://dev.w3.org/html5/spec-author-view/syntax.html#syntax-start-tag – Josh Crozier Dec 12 '15 at 04:59