jQuery Custom Events


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

jQuery Custom Events

Here we look at how create and use custom events in jQuery.

Well I wanted to find out how to do custom events in jQuery, this can potentially lead onto some interesting aspects of jQuery which may not be initially covered with just using jQuery for simple effects on the page.

jQuery Custom Events Example

Let's start with a bit of simple HTML, an example I've been using in many of these jQuery articles:


<div id="clickMe">
    Click Me
</div>


<div id="Saturn">
    Saturn
</div>

So we have a couple of divs, one called 'clickMe', and one called 'saturn'. What I'd like to do is wire up an event handler for the 'clickMe' div's click event, which will fire off a custom event we have created.

There are several ways to create a custom event, I'm going to use the jQuery .bind() method. You select a jQuery object for which the event will be bound to, and then using .bind() you create your new event as a callback function.

In the below code we create our custom event called 'Saturnmoving' and bind it to the element with the id of 'Saturn'. In this event we specify that the div of id 'Saturn' will have some full stops/periods prepended before element, almost having the effect of moving Saturn! We then wire up the click event on the div with id 'clickMe' so that in the code of this event, we manually fire off our newly created custom event using the .trigger() method.


<script type="text/javascript">

    $(document).ready(function () {

        $('#Saturn').bind("Saturnmoving", function () {
            $('#Saturn').before(".....");
        });

        $('#clickHere').bind("click", function () {
            $('#Saturn').trigger("Saturnmoving");
        });

    });

</script>