We can now utilize our JavaScript functions by referencing them as events in jQuery. A few of these events will save your life. Remember back when you used the HTML element attributes like onclick? Now, you can simply use the jQuery selectors that are listening the entire time the user is viewing the page. Listeners are useful so you are crowding your code with onclicks and other HTML action attributes. So, whenever you want to change an event, you can just go to your JavaScript code and not have to sift through your HTML.
As you can see, I select the ol, and then I select its first child li:first node. I Invoke the event hide, which basically sets the node’s style to invisible.
Events in jQuery are not limited to a single element. You can actually get fairly complicated passing in classes and names to have track events of any of the elements in that group. This is great practice as it is very dynamic and requires much less code than a ton of static JavaScript functions.
Common Events
- $(document).ready(function) – starts when the selector has been loaded (document is the common selector)
- $(selector).focus(function) – starts when the selector gains focus
- $(selector).mouseover(function) – starts when the user hovers over the element
- $("input").keypress(function) – starts when a key is pressed
- $("input").keydown(function) – starts when a key is pressed down
- $("input").keyup(function) – starts when a key is released
- $(window).scroll(function) – starts when the user scrolls the selector (window is the common selector)
These are just a few of the important events, but please feel free to go jQuery’s tutorial on events to see the rest of the events I cannot overstate the importance of the events in jQuery. Use them to control when and how you want to start jQuery functions.