Skip to content

Instantly share code, notes, and snippets.

@Harshit369
Created February 25, 2018 09:33
Show Gist options
  • Save Harshit369/12533d77d7a9cb3f17f80f86c91065f7 to your computer and use it in GitHub Desktop.
Save Harshit369/12533d77d7a9cb3f17f80f86c91065f7 to your computer and use it in GitHub Desktop.

Revisions

  1. Harshit369 created this gist Feb 25, 2018.
    31 changes: 31 additions & 0 deletions customEvents.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    // first add appropriate event listener.
    document.addEventListener('poke', function(e) {
    console.log(e.detail);
    })

    // create a new custom event from CustomEvent cunstructor.
    var pokeEvent = new CustomEvent('poke', {
    detail: 'giggles'
    });

    // dispatch event on element.
    document.dispatchEvent(pokeEvent); // logs "giggles".



    /* CustomEvent polyfill for some old IE version support */

    (function () {
    if (typeof window.CustomEvent === 'function') return false;

    function CustomEvent(eventName, params) {
    var params = params || { cancelable: false ,bubbles: false, detail: undefined };
    var evt = document.createEvent('CustomEvent');
    evt.initCustomEvent( eventName, params.bubbles, params.cancelable, params.detail );
    return evt;
    }

    window.CustomEvent = CustomEvent;

    window.CustomEvent.prototype = window.Event.prototype;
    })();