65.9K
CodeProject is changing. Read more.
Home

Binding Multiple Events in jQuery

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Sep 12, 2012

CPOL
viewsIcon

28800

Bind a JavaScript function to multiple events using jQuery

Introduction

Sometimes, we would like to use the same function for more than one event of an element. Normally, we create a function and call on different events. But sometimes we find, it is a duplication of calling function. I did some Googling and found a solution to use jQuery function.

A piece of code where I needed to call function twice:

    $("#textbox").click(
    function () {
        $(this).next().css("display", "none");
    }).focus(function () {
        $(this).next().css("display", "none");  
    });  

To avoid duplication, we will create a function and call from both the events. But still a function name will be duplicated there.

Now using jQuery, we can bind multiple events on single function. See here how we can make that simpler.

 $("#textbox").bind("click focus",
    function () {
        $(this).next().css("display", "none");
    });