Open In App

jQuery on() Method

The jQuery on() is an inbuilt method that is used to attach one or more event handlers for the selected elements and child elements in the DOM tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This method defines accessing elements in the DOM tree. 

Syntax:



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

Parameter: It accepts some parameters which are specified below-

Return Value: This returns all the event handlers that are attached to the selected element. 



Example 1: In the code below child specifier and data is not passed. 




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
    <script>
        /* jQuery code to show on method */
        $(document).ready(function () {
            $("p").on("click", function () {
                document.getElementById("p1").innerHTML
                    = "Paragraph changed!";
            });
        });
    </script>
 
    <style>
        #p1 {
            font-size: 30px;
            width: 400px;
            padding: 20px;
            border: 2px solid green;
        }
    </style>
</head>
 
<body>
    <!--click on this paragraph -->
    <p id="p1">Click Here !!!</p>
</body>
 
</html>

Output: 

Example 2: In the below code data and message both are being passed to the function. 




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
    <script>
        /* jQuery code to show on method */
        function handlerName(event) {
            let t = event.data.msg;
            document.getElementById("p1").innerHTML = t;
        }
 
        $(document).ready(function () {
            $("p").on("click", {
                msg: "You just clicked the given paragraph !"
            }, handlerName)
        });
    </script>
    <style>
        #p1 {
            font-size: 30px;
            width: 470px;
            padding: 20px;
            border: 2px solid green;
        }
    </style>
</head>
 
<body>
    <!--click on this paragraph -->
    <p id="p1">Click Me!</p>
</body>
 
</html>

Output: 


Article Tags :