As others have noted, the .click()
method call triggers the click event. Another gotcha is that, if a button has focus, even the spacebar will trigger the click event.
From a coding standpoint, I make it a practice to always use the .on( 'eventtype', handler_function )
form, rather than using the shorthand equivalents. I find it’s clearer and easier to understand. I also always use an event namespace (see the jQuery docs already posted) so that I can easily unbind events from the UI, if needed (very useful in a dynamic, changing interface).
Additionally, I do not use methods like .click()
or .change()
to trigger an event on the UI as that tightly binds your logic to the UI structure. (I have used it in the past and, wherever I find it, I refactor it out without mercy!).
It’s much better to extract the handler into its own function that all methods which need it can refer to. That way, if you change your UI structure or naming/IDs, you don’t break your JS in some unexpected way. It also allows you to use your handler function outside of UI interactions.
Finally, it’s a good idea to select elements once into variables and then use them without re-selecting them. That saves execution overhead (every time you do something like $( '#select' )
that element has to be found in the document … It’s unnecessary repetition. Saving to a variable also means that, if do you change the naming, you only have to change it in the variable declaration, not throughout the code.
So, your example might refactor out to something like …
const $search_input = $( '#search-input' );
const $search_button = $( '#search' );
$search_input.on( 'keydown', ( e ) => {
if ( e.which === 13 )
{
do_search( $search_input.val() );
return;
}
});
$search_button.on( 'click', () => do_search( $search_input.val() ) );
function do_search( search_value ){
/*
NOW YOUR SEARCH FUNCTION CAN BE CALLED AT ANY TIME, INDEPENDENT OF UI STATE
AND CAN BE PASSED IN ANY VALUE (EVEN A CACHED VALUE SO THAT YOU CAN RESTORE A PREVIOUS SEARCH EASILY).
*/
}
There are some other things you can do, like adding a setTimeout/clearTimeout to your keydown function handler so that you wait a certain amount of time before searching so that you aren’t hammering your search function with every keystroke (this is very useful especially in cases where you are fetching data via XHR or making large changes to the UI), but those are additional refinements.