Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    });
like image 760
chamara Avatar asked Aug 01 '13 07:08

chamara


People also ask

What is the jQuery method for attaching a custom event to an element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.

How is an event generated in jQuery?

These events are often triggered by the end user's interaction with the page, such as when text is entered into a form element or the mouse pointer is moved. In some cases, such as the page load and unload events, the browser itself will trigger the event.


2 Answers

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

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

Fiddle

like image 80
McGarnagle Avatar answered Oct 04 '22 01:10

McGarnagle


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();
    });
});
like image 45
andreister Avatar answered Oct 04 '22 00:10

andreister