Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom event in HTML, Javascript

I'm looking to create a custom event in HTML, JS.

<input type="text" oncustombind="foo(event);" />

How can I create one such? 'oncustombind' is the custom event I want to create. I should be able to call the function/code defined in the oncustombind attribute. Also, I need to pass some data to the event object.

I don't want to use any libraries such as jquery, YUI.

Any help would be deeply appreciated.

like image 340
varunvs Avatar asked Oct 28 '11 09:10

varunvs


People also ask

Can we create custom events?

Creating a Custom Event: To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality. The below steps are followed in order to create one using a new Event. We create an event using the Event constructor.

What are the two types of custom events?

Application Event: Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified. Component Event: A component event is fired from an instance of a component.

What is the use of a custom event?

A Custom Event is a URL page load event from your website that you'd like to track as a conversion. For example, an order confirmation page or a thank you page.


2 Answers

You want a CustomEvent

They should be easy to work with but browser support is poor. However the DOM-shim should fix that.

var ev = new CustomEvent("someString");
var el = document.getElementById("someElement");
el.addEventListener("someString", function (ev) {
    // should work
});
el.dispatchEvent(ev);
like image 105
Raynos Avatar answered Sep 19 '22 19:09

Raynos


It's bad practice to use new Function and with, but this can be accomplished as follows: http://jsfiddle.net/pimvdb/72GwE/13/.

function trigger(elem, name, e) {
    var func = new Function('e',

      'with(document) {'
    + 'with(this) {'
    + elem.getAttribute('on' + name)
    + '}'
    + '}');

    func.call(elem, e);
}

With the following HTML:

<input type="text" oncustombind="console.log(e, type, getElementById);" id="x">

then trigger the event like:

trigger(document.getElementById('x'), 'custombind', {foo: 123});
like image 34
pimvdb Avatar answered Sep 18 '22 19:09

pimvdb