Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!