How to use .on and .hover in jQuery?


jQuery- a popular JavaScript library used in simplifying web development tasks. It gives an easy-to-use syntax that simplifies coding and improves performance. Among the many features that jQuery provides, two of the most commonly used are .on() and .hover(). These methods allow to bind events to DOM elements and executing code when the events are triggered.

In this article, we will learn how to use .on() and .hover() in jQuery. We will see the different approaches to using the .on() and .hover() methods.

The .on() Method

The .on() method in jQuery is used in binding one or more events to a selected element. The method provides a flexible way to attach events to existing and dynamically created elements. The .on() method gives a lot of consistency to the API, and is recommended to use this method due to its simplifying process in the jQuery code base.

Syntax

Below is the syntax for using the .on() method in jQuery.

$(selector).on(event, childSelector, data, handler);

Parameters

  • selector − the selector of the element(s) to which the event will be bound.

  • event − the event(s) to be bound to the selected element(s).

  • childSelector (optional) − a selector for child elements of the selected element(s) that should trigger the event.

  • data (optional) − additional data to pass to the event handler function.

  • handler − the function to be executed when the event is triggered.

Example 1: Bind a Click Event

In the below example, we are using the default method to bind a click event. Here, we have used the $(document).ready() method to wait for the DOM to be fully loaded before executing the JavaScript code and used the .on() method to bind a click event to the button element on the page. Now, whenever the user clicks the button, an alert message is displayed.

<html>
<head>
   <title>How to use the .on() method in jQuery</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script>
      $(document).ready(function() {
         $("button").on("click", function() {
            alert("You just clicked me!");
         });
      });
   </script>
</head>
<body>
   <h2>Using the .on() method in jQuery</h2>
   <button>Click here</button>
</body>
</html>

Example 2: Binding Events to Dynamic Elements

In the below example, we have used the .on() method to bind a click event to the "Add Field" button on the page. When the button is clicked, a new input field is created using the jQuery $("<input>") method and appended to the form using the .append() method.

The .on() method binds a blur event to the form on the page. This event is triggered when an input field loses focus. We specify the "input" selector as the second argument to the .on() method, which tells jQuery to only listen for blur events on input elements that are descendants of the form element. When a blur event is triggered, we use the $(this) keyword to get a reference to the input field that triggered the event, and use the .val() method to get its value. We then display the value in an alert box.

<html>
<head>
   <title>How to use the .on() method in jQuery</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script>
      $(document).ready(function() {
         // Add new input fields when the "Add Field" button is clicked
         $("button").on("click", function() {
            var input = $("<input type='text' placeholder='Enter text here'>");
            $("form").append(input);
         });
         // Alert the user with the value of each input field when it loses focus
         $("form").on("blur", "input", function() {
            alert($(this).val());
         });
      });
   </script>
</head>
<body>
   <h2>Using the .on() method in jQuery</h2>
   <form>
      <input type="text" placeholder="Enter your text here">
      <button>Add here</button>
   </form>
</body>
</html>

Event Binding in .on() Method

The .hover() Method

The .hover() method in jQuery is used in binding two events i.e. mouseenter and mouseleave event to a selected element. This method allows us to execute different codes when the user hovers over an element and when they move their mouse away from it.

The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements.

Syntax

Below is the syntax for using the .hover() method in jQuery.

$(selector).hover(handlerIn, handlerOut);

Parameters

  • selector − the selector of the element(s) to which the event will be bound.

  • handlerIn − the function to be executed when the user hovers over the element.

  • handlerOut − the function to be executed when the user moves their mouse away from the element.

Example: The Default Method

In the below example, we have used the $(document).ready() method to wait for the DOM to be fully loaded before executing the JavaScript code and also used the .hover() method to bind two events (mouseenter and mouseleave) to the div element on the page. Now, when the user hovers over the div, the background color is changed to violet using the .css() method. When the user moves their mouse away from the div, the background color is changed back to green.

<html>
<head>
   <title>How to use the .hover() method in jQuery</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <style>
   div {
      width: 200px;
      height: 200px;
      background-color: green;
      border: 1px solid black;
   }
   </style>
   <script>
      $(document).ready(function() {
         $("div").hover(function() {
            $(this).css("background-color", "violet ");
         }, function() {
            $(this).css("background-color", "green");
         });
      });
   </script>
</head>
<body>
   <h2>Using the .hover() method in jQuery</h2>
   <p>Hover over the below DIV to see the effect.</p>
   <div></div>
</body>
</html>

Conclusion

The .on() and .hover() methods in jQuery are powerful tools that make it easier to bind events to DOM elements and execute code when those events are triggered. The .on() method provides a flexible way to attach events to existing and dynamically created elements, and the .hover() method allows us to execute different codes when the user hovers over an element and then moves their mouse away from it. By understanding the syntax and different approaches to use these methods, developers can create more dynamic and interactive web applications with ease.

Updated on: 04-May-2023

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements