How to pass a jQuery event as a parameter in a method?

To pass a jQuery event as a parameter in a method, you can use the bind() method or modern event handling methods like on(). The event object contains useful information about the triggered event and can also carry custom data through the event.data property.

Example

You can try to run the following code to learn how to pass a jQuery event as a parameter ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn1").bind("click", { key1: "value1", key2: "value2" }, myFunction);
            
            function myFunction(event) {
                $("#myid").text("Data received: " + event.data.key1);
            }
        });
    </script>
</head>
<body>
    <input id="btn1" type="button" value="Click Me" />
    <div id="myid" style="border:2px solid blue; width:400px; height:100px; padding:10px;">
        Click the button to see the event data
    </div>
</body>
</html>

The output of the above code is ?

When you click the button, the div will display: "Data received: value1"

Modern Approach with on() Method

While bind() works, the modern approach uses the on() method ?

$("#btn1").on("click", { key1: "Hello", key2: "World" }, function(event) {
    console.log(event.data.key1); // Outputs: Hello
    $("#myid").text(event.data.key2);
});

Conclusion

jQuery events can be passed as parameters to methods using bind() or on(), allowing you to access event data and handle user interactions effectively. The event object provides access to custom data through event.data property.

Updated on: 2026-03-13T19:06:41+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements