Attaching an event to an element with jQuery
Posted February 24th, 2009 in Javascript
My last jQuery post looked at jQuery's document ready initialization function which you can use to do stuff to prepare your web page, including things such as attaching an event to an element which I will look at how to do in this post.
The following example uses an input button with the id "example_button". Note that the tag contains no Javascript at all.
<input type="button" value="Click Me!" id="example_button" />
In the document ready function we can attach an event handler to the click() event of the button which pops up an alert dialog to show the button has been clicked like so:
$(document).ready(function() {
$('#example_button').click(function() {
window.alert("You clicked me!");
});
});
The button below shows the above code working in action. Note that this will not work in a feed reading application so you'll need to click through to this post on my blog for it to work.
There are a number of events you can attach to an element and these include things like: hover (which I'll cover on Thursday next week because it's slightly different), blur, click, focus, keypress, mouseup and scroll. Obviously some will have no effect on some elements such as scroll on a button. I'll look at some of these other events in future jQuery posts so be sure to subscribe to my RSS feed (details below) so you don't miss out.
Related posts:
- How to tell if an element exists with jQuery (Friday, April 10th 2009)
- jQuery's document ready initialization (Friday, February 20th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
- Adding, removing and checking if an element has a CSS class with jQuery (Tuesday, December 16th 2008)
- How to get and set form element values with jQuery (Thursday, November 13th 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
