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!!!');
});
});
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.
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.
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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With