Jade + Javascript does not work

0

I have a template .jade

extends layoutIn

block content

    input(type="text", id="captureInput", style="width:100%")
    pre(id="resultado", style="overflow-y: scroll; height:150px")

and the javascript is:

var texto       = document.getElementById('captureInput'),
    resultado   = document.getElementById('resultado'),
    teclas      = {}; //acá guardamos tiempo de inicio y fin de cada tecla
alert("1");
texto.addEventListener('keydown', function(keyboardEvent) {
    alert("2");
    const timestamp = performance.now(),
          keyName   = keyboardEvent.key;

    if (!teclas[keyName]) { //Sólo si no se está manteniendo presionado
        teclas[keyName] = {down: timestamp};
    }
});
  

shows the first alert, but the second never.

NOTE: The same code with jquery works 100% with the following code jquery works

$(function () {
            var captureInput = $('#captureInput');
            $(captureInput).focus();

                $(captureInput).keydown(function(event){ //inicio de presion
                    var timeDown = (new Date()).getTime();
                    var keyName=event.keyCode;
                    if (!teclas[keyName]) { //Sólo si no se está manteniendo presionado
                        teclas[keyName] = {down: timeDown};
                    }                     
                });
    
asked by hubman 19.11.2016 в 16:06
source

1 answer

2

To work in any browser you have to wait for the document object to be ready to use. Your javascript code must be put in a load event:

window.addEventListener('load', function(){
    var texto       = document.getElementById('captureInput'),
        resultado   = document.getElementById('resultado'),
        teclas      = {}; //acá guardamos tiempo de inicio y fin de cada tecla
    alert("1");
    texto.addEventListener('keydown', function(keyboardEvent) {
        alert("2");
        const timestamp = performance.now(),
              keyName   = keyboardEvent.key;

        if (!teclas[keyName]) { //Sólo si no se está manteniendo presionado
            teclas[keyName] = {down: timestamp};
        }
    });
});

The use of

window.addEventListener('load', function(){

is equivalent in jQuery to:

$(function () {

and what it is doing is waiting for the document to be ready to be used

    
answered by 19.11.2016 / 16:57
source