简体   繁体   中英

Simple custom event in jquery

I'm trying to learn jquery custom events.

I need to fire a simple event on page load.

HTML:

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

I need to call my own event to fire an alert

$("#mydiv").custom();

i tried the below code.

function customfun()
    {
        $("#mydiv").trigger("custom");
    }

    $(document).ready(function () {

        $("#mydiv").bind(customfun, function () {
            alert('Banana!!!');
        });

    });

You need to bind to the same event name -- "custom" -- as the one you triggered. Like this:

$("#mydiv").on("custom", function () { ...

Fiddle

To call custom events as jquery functions you need, well, define such a function via $.fn :

$(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;
    };

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

you can call it by doing so:

$.fn.mycustom = function(){
     return this;
};

$("div").mycustom();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM