chamara
chamara

Reputation: 12711

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!!!');
        });

    });

Upvotes: 5

Views: 309

Answers (3)

McGarnagle
McGarnagle

Reputation: 102743

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

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

Fiddle

Upvotes: 4

andreister
andreister

Reputation: 13871

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

Upvotes: 2

maverickosama92
maverickosama92

Reputation: 2725

you can call it by doing so:

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

$("div").mycustom();

Upvotes: 0

Related Questions