Skip to Content

Advertisement

You (Level 0)
0% Complete
Last Badge Earned
None

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.

Example <button>Click Me!</button>
<ol>
<li>
Item 1
</li>
<li>
Item 2
</li>
</ol>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$("button").click(function()
{
$('ol li:first').hide();
});
</script>

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.

I've attached my favorite JavaScript and jQuery book. I would encourage you to read it as well.

Your code will execute in this window.



Let's explore some more tutorials or topics!

Next Tutorial Previous Tutorial

Advertisement

If you enjoyed this resource, support me by sharing this page with others.

Comment on

Show Comments

No comments yet... Be the first!



Advertisement