Lesson 7 – jQuery Events

Events allow you to create dynamic web pages in jQuery. Events are actually different kinds of actions including but not limited to the following.

  • A web page loading
  • A mouse click
  • Submitting a form
  • Hovering mouse over an element
  • Stroking a key on your keyboard.

All the modern web browsers have the ability to detect these actions. Once the browser triggers these functions, you can do whatever you want by creating custom functions. These custom functions are commonly referred to as Event Handlers.

In the example below, we are going to display an alert when any of the boxes is clicked using the “click” event.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Events</title>
    https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js

    
      $(document).ready(function () {
        $('div').bind('click', function (event) {
           alert ('Hello World!');
        });
      });
    

<style>
     div { 
        margin: 10px;
        padding: 12px; 
        border: 2px solid #666; 
        width:60px;
     }

     #box1 {
        background-color:blue;
     }

     #box2 {
        background-color:yellow;
     }

     #box3 {
        background-color:green;
     }
  </style>
</head>

<body>   
  
Click on me
Click on me
Click on me
</body> </html>

The alert “Hello World!” will be shown when the user clicks inside any of the boxes. The division element actually responds to the click event and the browser displays the alert as a result. We also have to bind the event to the DOM element in jQuery. We use the bind() function to accomplish this task.

This is a very, very simple example of manipulating DOM with the help of jQuery events. In fact, jQuery has numerous events that perform different types of tasks. Some of these events include:

  • blur: The event occurs when the element loses its focus.
  • focus: The event occurs when the element is focused.
  • dblclick: The event occurs when the user double clicks the mouse.
  • keydown: The event occurs when user presses a key on the keyboard.
  • resize: The event occurs when a user resizes the browser window

In the next lesson, we will talk about creating visual effects with the help of jQuery.