Home / Attaching an event to an element with jQuery

Attaching an event to an element with jQuery

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.