Prevent evenListener when input is in focus

I ended up finding a solution to my problem with the help of expressjs123.

In order for the code to work for all of my input tags I had to use getElementsByTagName which creates a list of all my input tags which I then iterated with a for-loop.

Setting an eventListener for “click” so focus equals true and one for ‘blur’ so focus equals false when leaving an input field.

An example can be viewed here!

let focus = false;
let inputList = document.querySelectorAll("input[type=text]");
for (let i = 0; i < inputList.length; i++) {
  inputList[i].addEventListener('click', () => {
    focus = true;
  inputList[i].addEventListener('blur', () => {
    focus = false;

document.addEventListener("keydown", (e) => {
  if (focus == false) {
    if (e.code == "KeyR") {
    } else if (e.code == "KeyG") {

function redBGcolor() {

function greenBGcolor() {
.red {
  background-color: red;

.green {
  background-color: green;

input {
  margin-top: 5px;
<body id='bod'>

  <input type="text" id="fname"><br>
  <input type="text" id="lname"><br>
  <input type="text" id="mname"><br>
  <input type="text" id="tname"><br>


CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top