Skip to content

Infinite event loop #6

@agka

Description

@agka

Because the polyfill listen to any selectionChange event to trigger a synthetic input event, if one is to call setSelectionRange() from within a input event handler, then an infinite event loop occurs (setSelectionRange() does trigger a selectionChange).

My take, cause I'm aware that this project is not really alive, and also too lazy to do a proper PR

(function ($nav, $doc) {
    "use strict";

    var $targetInput;

    function isTextField($elem) {
        return $elem.tagName === "TEXTAREA" || ($elem.tagName === "INPUT" && $elem.type === "text");
    }

    // using bitwise NOT to compare against -1 as  ~(-1) returns 0
    // (~indexOf) is similar to (indexOf != -1)
    if (~$nav.userAgent.indexOf("MSIE 9")) {
        $doc.addEventListener("keydown", function (e) {
            // 8    backspace
            // 46   delete
            if (isTextField(e.target) && ~[8, 46].indexOf(e.which)) {
                $targetInput = e.target;
            }
        });

        $doc.addEventListener("cut", function (e) {
            // Note: cut is triggered before the action
            if (isTextField(e.target)) {
                $targetInput = e.target;
            }
        });

        $doc.addEventListener("selectionchange", function () {
            var event;

            if ($targetInput && $targetInput === $doc.activeElement) {
                event = $doc.createEvent("CustomEvent");
                event.initCustomEvent("input", true, false, {});
                $targetInput.dispatchEvent(event);
                $targetInput = null;
            }
        });
    }
})(navigator, document);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions