jQuery Introduction | Event Handling | Event Concepts (Event Handler, Event Object)

What Is an Event?

A web page performs many interactions with users. Users perform many kinds of actions, such as moving the mouse, clicking elements, or typing in a text box.

All of these user actions generate events. In other words, when an event occurs, it means that a specific action has occurred on the web page and the web browser reports that fact.

Event Handler

Many events continuously occur on a web page. To handle an event that occurs on a specific element, you must write and connect a function called an event handler. When an event of the specified type occurs on the specific element to which the event handler is connected, the web browser runs the connected event handler.

The following example creates and connects event handlers.

$("p").on({
    mouseenter: function() {
        $(this).css("background-color", "yellow");
    },
    mouseleave: function() {
        $(this).css("background-color", "blue");
    },
    click: function() {
        $(this).css("background-color", "red");
    }
});

Event Object

When an event handler function is called back by jQuery, an event object is passed to the function as an argument. With the event object that is passed in, you can determine event characteristics or prevent the default behavior of the event. jQuery’s event object normalizes the event object that follows the W3C standard recommendation.

Commonly used properties and methods include the following.

  • type: Event type
  • pageX: Mouse X coordinate relative to the browser screen
  • pageY: Mouse Y coordinate relative to the browser screen
  • preventDefault(): Removes the default event behavior.
  • stopPropagation(): Stops event propagation.

More - http://api.jquery.com/category/events/event-object/

The following example shows the difference between preventDefault() and stopPropagation().

// No method call
$("#text1").on("click", function(e){
    $(this).css('color', 'green'); 
});

// Call preventDefault
$("#text2").on("click", function(e){
    $(this).css('color', 'green');

    e.preventDefault();
});

// Call stopPropagation
$("#text3").on("click", function(e){
    $(this).css('color', 'green');

    e.stopPropagation();
});

// Call both
$("#text4").on("click", function(e){
    $(this).css('color', 'green');

    e.preventDefault();
    e.stopPropagation();
});

$("div").on("click", function(e){
    $(this).css('background-color', 'yellow');         
});

Use preventDefault() to remove the default event behavior of the <a> tag. Use stopPropagation() to prevent the event from propagating to the <div> tag.

Run code

Reference

http://api.jquery.com/category/events/event-object/