Friday, January 3, 2014

Bind or unbind event to control using jquery

We can bind or unbind events to controls using JQuery.

The JQuery method .on() we will use for binding events and method .off() we will use for unbind the events.



$("#btnClickMe").on("click", function () {

alert("click event added using JQuery");

});

.on() is the JQuery method to bind events,

In the above example we have passed two parameters to the method .on(),

one is event to be perforemed and another is the function to perform action when event is raised.

i.e. "click" is the argument represents the event followed by function which specifies the actions to be performed.

Bind multiple events using .on() method

We can bind multiple events using .on() method, Suppose when mouse enter or leave a div you want to fire an event,

both the events we can write at a time using .on() method.

<script language="javascript">

$("#divSample").on("mouseover mouseleave", function () {

$(this).fadeOut(1000, function () { $(this).fadeIn(); });

});

</script>







Bind events using .one() method

If you want to fire a particular event only once then use the method .one() to bind the event,

then the event fires only once. The parameters and syntax for the method .one() is same like for the method .on()

<script language="javascript">

$("#divonce").one("mouseover mouseleave", function () {

$(this).fadeOut(1000, function () { $(this).fadeIn(); });

});

</script>

UnBind events using .off() method

If you want to unbind a particular event use .off() method. In the below example click on "Bind" button to bind the

mouserover event to div to fadein fadeout and click "UnBind" to unbind the mouseover event

<script language="javascript">

$("#btnbind").on("click", function () {

$("#divbindunbind").on("mouseover", function () {

$(this).fadeOut(1000, function () { $(this).fadeIn(); });

});

});

$("#btnunbind").on("click", function () {

$("#divbindunbind").off("mouseover");

});

</script>

No comments:

Post a Comment