jQuery > Events

Custom event in jQuery

What is custom event and how to attach a custom event to an element?

What is Custom event in jQuery?

Custom event is a event name defined by us and it is a special type of event that allows us to add any functionality on a particular element. This event is similar to any other type of inbuilt events like “click, mouseenter” however its behavior is not pre-defined instead we have ability to define its behavior.

See example code below

  <div id="divCustom" style="border: 1px solid #c0c0c0; padding: 5px; padding: 10px;">
        DotNetFunda.com | ItFunda.com
<input type="button" id="btnCustomEvent" value="Trigger Custom Event" />
<div id="divDemo" style="font-size: 50px;">Demo Text</div>
<script type="text/javascript"> function MyFunction() { $("#divDemo").slideUp().delay("500").slideDown(); }
$("#divCustom").bind("myCustomEvent", MyFunction);
$("#btnCustomEvent").click(function () { $("#divCustom").trigger("myCustomEvent"); });

In the above code snippet, a custom event named “myCustomEvent” is bound to the “divCustom” div element that fires javascript function MyFunction when called. On click of the “btnCustomEvent” button, we have triggered “myCustomEvent” event that calls the MyFunction.

 Views: 827 | Post Order: 89

Write for us