jQuery Custom Events


InterServer Web Hosting and VPS
Sony Playstation PS4 Pro Custom Build NVMe SSD Drive - Enclosure case and Crucial NVMe SSD
PS4 Pro Custom External SSD NVMe Drive

How I built a PS4 Pro Custom External SSD NVMe Drive...

NUC8i7BEH with memory
Intel NUC8I7BEH Review and Custom Build

This is my review of the Intel NUC8i7BEH and a summary of my build...

Card image cap
Asus M5A88-M EVO Review

This is my review of the Asus M5A88-M EVO motherboard...

Corsair Vengeance Blue 8GB (2x4GB) DDR3 PC3-12800C9 1600MHz Dual Channel Kit
Corsair Vengeance Blue Review

This is my review of the Corsair Vengeance Blue 8GB (2x4GB) DDR3 PC3-12800C9 1600MHz Dual Channel Kit memory...

Robotic Arm with USB PC Interface Review
Robotic Arm with USB PC Interface Review

This is my review of the Robotic Arm with USB PC Interface...

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>

Sponsored Links
SolarSystem - AngularJS Demo
SolarSystem - Angular JS Demo

Check out my first Angular JS demo hosted in Azure, it helped win my first Angular contract. Put the sound on.