Search code examples
javascripteventsbrowser-feature-detection

How can I test for browser support for an event


Specifically, testing to see if input[type=date] fires the input event?


Solution

  • By looking at this website, I'd suggest you try

    Test B: Use setAttribute on an input to set an oninput and check to see if node.oninput is a function Test C: Use the w3 event api to create an input and fake a keypress to see if oninput fires

    Here is the JavaScript from Test C

    function testC(){
        var input = document.createElement('input'),
            e = document.createEvent("KeyboardEvent");
        // set type for DATE
        input.setAttribute('type', 'date');
        e.initKeyEvent("keypress", true, true, window, false, false, false, false, 0, "e".charCodeAt(0));
        // use initKeyboardEvent for webkit
        document.body.appendChild(input);
        input.addEventListener("input", function(e) { alert('C Successful'); e.preventDefault(); e.stopPropagation(); }, false);
        input.focus();
        input.dispatchEvent(e);
        document.body.removeChild(input);
    }
    

    Edit: The test code is copied from the test page with only a couple minor changes (position of var, type=date, alert). I ran it in chrome (after changing initKeyEvent to initKeyboardEvent) just now and it doesn't result in anything, however commenting out the removeChild line and doing it manually does result in success message. Not sure why the simulated event didn't invoke it so you'd need to look over this before applying it in your code.