Sunday, August 4, 2013

Simple Custom Event Example in Jquery


Code will demonstrate how to trigger a custom event on DIV click to fire a simple alert message.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>

    $(document).ready(function () {
        //define the event
        $(document).on('custom', function () {
            alert('Custom event!');
        });

        //define the function to trigger the event (notice "the jquery way" of returning "this" to support chaining)
        $.fn.custom = function () {
            this.trigger("custom");
            return this;
        };

        $(document).on("custom2", function () {
            alert("custom 2");
        });

        $.fn.custom2 = function () {
            this.trigger("custom2");
            return this;
        };

        //trigger the event when clicked on the div
        $("#mydiv").on("click", function () {
            $("#mydiv").custom().custom2();//trigger custom events with chaining
        });
    });

</script>

<div id="mydiv"> my div</div>

No comments:
Write comments
Recommended Posts × +