Open In App

How to use .on and .hover in jQuery ?

jQuery .on() method: This method is used to attach an event listener to an element. This method is equivalent to the addEventListener in vanilla JavaScript.

Syntax:



$(element).on(event, childSelector, data, function)

Parameter

Example:




<!DOCTYPE html>
<html>
  
<head>
    <!-- Adding jQuery Library -->
    <script src=
    </script>
  
    <style>
        /* Adding basic styling */
        div {
            background-color: green;
            width: 100px;
            height: 100px;
            color: #fff;
            text-align: center;
        }
    </style>
</head>
  
<body>
    <div>Normal</div>
    <script>
        $('div').on('click', function () {
  
            // Changing the content
            $(this).html('Clicked!');
        });
    </script>
</body>
  
</html>

Output:



jQuery .hover() method: This method is used to specify the styles of the element during mouseover and mouseout conditions. It takes two functions as an argument:

You can specify multiple styles inside these functions.

Syntax:

$(element).hover(mouseoverFunction, mouseoutFunction)

Example:




<!DOCTYPE html>
<html>
  
<head>
    <!-- Adding jQuery Library -->
    <script src=
    </script>
  
    <style>
        /* Adding basic styling */
        div {
            background-color: green;
            width: 100px;
            height: 100px;
            color: #fff;
            text-align: center;
        }
    </style>
</head>
  
<body>
    <div>Normal</div>
      
    <script>
        $('div').hover(function () { // mouse-in 
            $(this).css("background-color", "blue");
            $(this).html('Hovered!');
        },
            function () { // mouse-out
                $(this).css("background-color", "green");
                $(this).html('Normal');
            }
        )
    </script>
</body>
  
</html>

Output:


Article Tags :