Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda