jQuery

Events

Events# Bind Handle


jQuery Event Methods

An event is triggered when a user performs an action like clicking or hovering.

There are many different types of events, including (there are more):

jQuery provides a cross-browser event model that works in IE, Chrome, Opera, FireFox, Safari and more. With jQuery we can bind specific behavior to a particular event. jQuery event model is simple to use (comparing to traditional JavaScript event handling) and provides a compact syntax.

The following table shows some of the event methods. See more at Category: Events.

Some Event Methods
Method Description Documentation
.click() Binds an event handler to the click JavaScript event .click()
.dblclick() Binds an event handler to the double click JavaScript event .dblclick()
.hover() Binds an event handler to the hover JavaScript event .hover()
.ready() Binds an event handler to the ready JavaScript event .ready()
.resize() Binds an event handler to the resize JavaScript event .resize()
.scroll() Binds an event handler to the scroll JavaScript event .scroll()
.keydown() Binds an event handler to the keydown JavaScript event .keydown()
.keyup() Binds an event handler to the keyup JavaScript event .keyup()
.keypress() Binds an event handler to the keypress JavaScript event .keypress()

Assigning Event Handlers

.click( handler( eventObject ) ) is used in jQuery to listen for a click event or trigger a click event on an element. For example:

    <div id="but1">Button1: Click me please</div>
    <div id="but2">Button2: Click me please and I will click Button1</div>
    <script>
        $( '#but1' ).click( function() { alert( "The element but1 was clicked" ); } );
        $( '#but2' ).click( function() { $( '#but1' ).click(); });
    </script>
Button1: Click me please
Button2: Click me please and I will click Button1

The above code you can write in a few ways. For example (I prefer .on over .click - see below):

    <script>
        $( '#but1' ).on( 'click', function() { alert( "The element myID was clicked" ); });
        $( '#but2' ).on( 'click', function() { $( '#but1' ).trigger( 'click' ); });
    </script>

on() - Works for dynamically added elements, and it has the ability to create delegated event handlers. Allows multiple events to be bound to one or more elements. Event names to bind are separated with a space. For example:

    $( '#but1' ).on( 'mouseenter mouseleave', function() {
        $( this ).toggleClass( 'entered' );
    });

off() - To remove the event, use off instead of on. For example:

    $( '#but1' ).off();

To remove specific event, use off( event ) . For example:

    $( '#but1' ).off( 'click' );

The following chart demonstrates how you have to use jQuery (note: type="text/javascript" is not required in HTML5):