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") {
      redBGcolor();
    } else if (e.code == "KeyG") {
      greenBGcolor();
    }
  }
})

function redBGcolor() {
  document.getElementById("bod").classList.add('red');
  document.getElementById("bod").classList.remove('green');
}

function greenBGcolor() {
  document.getElementById("bod").classList.add('green');
  document.getElementById("bod").classList.remove('red');
}
.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>

</body>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top