JQuery Events

In JavaScript, events are essential for creating interactive and dynamic web experiences, and jQuery provides a powerful set of tools to handle them seamlessly. As you've already seen, events are actions that are triggered on a certain interaction within the browser, and it's possible to detect them within your web application. 

Desired Outcomes:

  • Understand the concept of events in web development and why they are important.
  • Recognize common events such as page loading, mouse clicks, double clicks, focus, element changes, hover, and form submission.
  • Know how to use jQuery to attach event handlers to HTML elements.
  • Write JavaScript functions that respond to specific events, enabling dynamic behavior in your web application.
  • Implement event handling for different user interactions, enhancing the user experience of your web pages.

Some of the mentioned events include:

  • page loading
  • mouse click
  • double mouse click
  • mouse hover over an element
  • sending an HTML form
  • etc.

When events are caught, it is possible to write arbitrary functions within them to perform any tasks. 

The following list includes the most commonly used jQuery events. Using these methods, it is possible to define event handling:

  • $(document).ready(function) - called only when the HTML document is fully loaded in the web browser
  • $(selector).click(function) - called by mouse clicking on the element
  • $(selector).dblclick(function) - called by double-clicking the mouse on the element
  • $(selector).focus(function) – called when the selected HTML element is in focus or active
  • $(selector).change(function) – called when the mentioned element changes
  • $(selector).hover(function) – called when the mouse pointer hovers over the element
  • $(selector).submit(function) – called when sending an HTML form

 If the event handling function returns false, further event processing is stopped.

In the following example, the .click(function) event is fetched on the <a> element, after which the color of the element is changed using the .css() method.

In the event function, $(this) is a DOM object that allows access to the methods of the jQuery object on which the function was triggered. By applying the $(this) object, only the link the user clicked on will be colored.

In the example above, you've probably noticed something else new, and that's the .preventDefault(); method. The preventDefault() method prevents the processing of predefined element events, and to use it, it is necessary to pass a parameter to the function on which the method is called. In the case of an empty link, the web page would return to the top of the document. By applying the preventDefault() method, the mentioned functionality will be disabled.

Document Ready Event

The $(document).ready(function () { ... }) event is triggered when the HTML document is fully loaded and ready for manipulation. It ensures that the enclosed code runs only when the document is ready.

<script>
  $(document).ready(function() {
      // Code here will execute when the HTML document is fully loaded.
      // This ensures that your JavaScript runs after the HTML elements are ready.
      alert("Document is ready!");
  });
</script>

The $(document).ready(function) is used to define code that should be executed when the HTML document is fully loaded in the web browser.

It ensures that your JavaScript code runs after all HTML elements are available, preventing issues with trying to manipulate elements that haven't been loaded yet.

Click Event

<button id="myButton">Click Me</button>
<script>
    $("#myButton").click(function() {
        alert("Button clicked!");
    });
</script>

The $(selector).click(function) attaches a click event handler to the selected element, in this case, a button with the ID "myButton."

When the button is clicked, the code within the function is executed, displaying an alert message.

Double Click Event

<div id="myDiv">Double click me</div>
<script>
    $("#myDiv").dblclick(function() {
        alert("Double-clicked!");
    });
</script>

The $(selector).dblclick(function) binds a double-click event handler to the selected element (a div with the ID "myDiv").

When the element is double-clicked, the function is triggered, displaying an alert.

Focus Event

<input id="myInput" type="text" placeholder="Click to focus">
<script>
    $("#myInput").focus(function() {
        $(this).css("background-color", "#e6e6e6");
    });
</script>

The $(selector).focus(function) attaches a focus event handler to the selected input element (with the ID "myInput").

When the input gains focus (is clicked or selected), the function changes its background color to light gray.

Change Event

<select id="mySelect">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
</select>
<script>
    $("#mySelect").change(function() {
        var selectedValue = $(this).val();
        alert("Selected option: " + selectedValue);
    });
</script>

The $(selector).change(function) binds a change event handler to the selected select element (with the ID "mySelect").

When an option is selected within the select element, the function is called, retrieving the selected option's value and displaying it in an alert.

Hover Event

<div id="myDiv">Hover over me</div>
<script>
    $("#myDiv").hover(
        function() {
            $(this).css("background-color", "#e6e6e6");
        },
        function() {
            $(this).css("background-color", "");
        }
    );
</script>

The $(selector).hover(function) attaches two event handlers to the selected element (a div with the ID "myDiv").

The first function is executed when the mouse pointer enters the element, changing its background color.

The second function is executed when the mouse pointer leaves the element, resetting its background color.

Form Submit Event

<form id="myForm">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <input type="submit" value="Submit">
</form>
<script>
    $("#myForm").submit(function(event) {
        event.preventDefault(); // Prevent the form from submitting
        var formData = $(this).serialize();
        alert("Form data: " + formData);
    });
</script>

The $(selector).submit(function) attaches a form submit event handler to the selected form element (with the ID "myForm").

When the form is submitted (by clicking the submit button), the function is called. The event.preventDefault() prevents the form from submitting in the traditional way. The serialize() method is used to serialize the form data, and an alert displays the form data.

Updated on:

Part of our complete: JQuery guide

Want exercises and real projects for this lesson? Get the full course.