An event is when something happens in an application. Event programing makes use of those events by setting up listeners to know when something happens. A listener is triggered when it “hears” the event broadcast, and it executes a function. This is how a program can respond to those events, making the page interactive.
There are many different events out there, but the most common ones used include:
- document.ready – when the HTML is loaded, and the DOM has been loaded into the browser
- click – when a user clicks on an element
- change – when a value in a form field changes
- keypress (and key up / key down) – when a key is pressed.
Different browsers handle events differently. However, jQuery tries to simplify them by removing some of the differences for you.
By default, the event runs through every element in the tags hierarchy. This can be helpful or harmful, so it is important to note is that you can prevent an event from moving up the chain.
Setting Up Event Listeners
jQuery makes it easy to attach an event listener to an element. Essentially it starts with a selector, then the ., then specify which event you want to use. These are the ways that jQuery gives us shortcuts.
$('#submit').click();
The function call can be an anonymous function, or a named function that is created/listed someplace else, but referenceable at this location.
If we will be having several events need the same function – then we should create a named function.
Anonymous Functions
Anonymous functions are functions that are directly attached to an event listener, and therefore cannot be called a name. They are most often used when a function will only be needed by a single element, and therefore, it is easier to write it directly into the event handler.
Anonymous functions are usually passed into the event handler as in the following example.
$('#submit').click(function() { alert('about to send the form'); // do some more stuff here... });
Notice that the function can spread over several lines, and in fact, normally does. Here, we put the closing brace (}) and the closing parentheses on the same line, along with the closing semi-colon.
Forcing an Event to Occur
But what would happen if we “forgot” to pass in a function reference. Well, this is something we can do intentionally.
jQuery will allow us to do this, and in fact it triggers the event handler for us. This is sometimes helpful if we want to start a page load with some initialization functions. I do this to place sliders in jQueryUI initially, if data is loaded on the page, before the user has a chance to move the slider.
To do this, you of course need to have an event handler set up first. This would be something like:
$('#buttona').click(function() { // do stuff when the button is pressed }); $('#buttona').click(); // force the event to occur
Introduction to Event Handlers in jQuery was originally found on Access 2 Learn
One Comment
Comments are closed.