Event keypress dodaje od razu do inputa znak

0

Próbuję dojść dlaczego jak kliknę guzik poza inputem to przez searchInput.focus(); dodaje mi znak do inputa. Czy to by oznaczało, że znak dodaje się w momencie kiedy podnoszę przycisk?

document.addEventListener('DOMContentLoaded', function () {

    (function () {
        document.addEventListener('keypress', function (e) {
            var searchKeyPressed = e.keyCode === 115;
            var target = e.target;
            var header = document.getElementsByTagName('header')[0];
            var searchInput = document.getElementById('q');

            if (!searchKeyPressed || target.className == "global-search")
                return false;

            if (header.style.paddingTop) {
                header.removeAttribute('style');
            } else {
                header.style.paddingTop = "50px";
                searchInput.focus();
            }
        });
    }());

}, false);
1

prawdopodobnie zależy to od przeglądarki, z keyup, keydown i keypress są różne jaja, bo w każdej przeglądarce jakiś szczegół się różni

0

Zrobiłem tak :

document.addEventListener('DOMContentLoaded', function () {

    (function () {
        function toggleGlobalSearch(e) {
            var searchKeyPressed = e.keyCode === 83; //zmiana
            var focusOnSearch = e.target.id === 'q';
            var clickedOutsideSearch = e.type === "click" && e.target.id !== 'q';

            var header = document.getElementsByTagName('header')[0];
            var searchInput = document.getElementById('q');

            if (!focusOnSearch && searchKeyPressed) {
                header.style.paddingTop = '50px';
                searchInput.focus();
                searchInput.value = "";
            }

            if(clickedOutsideSearch && header.style.paddingTop) {
                header.removeAttribute('style');
            }
        }

        document.addEventListener('keyup', toggleGlobalSearch, false); //zmiana
        document.addEventListener('click', toggleGlobalSearch, false);
    }());

}, false);

I działa tylko po pierwsze nie rozumiem dlaczego? A po drugie dlaczego jak używam event keyup to mój keyCode to 83, a jak keypress to 115?

@Edit odpowiedź na moje pytanie

The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two.

1 użytkowników online, w tym zalogowanych: 0, gości: 1