Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
Trapping keydown with basic JavaScript

I am fairly new to coding (Doing the foundation course on The Odin Project).
I am having some problems with the calculator project.

I want the calculator to be driven by both mouse & keyboard.
But when I press keys like "/", "." these are not trapped by Firefox or Chrome additionally Chrome is not trapping some more keys like "-" & "+".

window.addEventListener("click", mouseClick);
window.addEventListener("keydown", keyPress);

The keyPress function simply calls the element.click() so that mouseClick() is emulated.

It seems if I press the above keys - the keys are not trapped by the "click" event handler.

Any help will be highly appreciated.

My System Details: Firefox 93.0 / Chrome 94.0.4606.81 on Fedora 34 x64.

The two functions are below, as requested: A small addition: I have uBlock Origin/ Bitwarden installed in Firefox (no addons on chrome), but I guess they should not interfere in anyway?

window.addEventListener("click", mouseClick); window.addEventListener("keydown", keyPress);

function keyPress(event){
    let keyCode = event.keyCode;
    if(keyCode === 13){
        keyCode = 61;
    }
    let btnPressed = document.querySelector(`button[data-key="${keyCode}"]`);
    if(!btnPressed){
        return;
    }
    console.log(btnPressed);
    btnPressed.click(); };

function mouseClick(event){
    if(!(event.target.tagName === "BUTTON")){
        return;
    }
    let currentButton = event.target.textContent;
    if(event.target.classList.contains("num-key")){        
        if(tmpNumArray.some(item => (item === ".")) && currentButton === "."){
            return;
        }
        tmpNumArray.push(currentButton);
        currNum = tmpNumArray.join("");
        refreshDisplay();
    }else{
        alert ("pressed operator");
    } };
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda