JavaScript JavaScript and the DOM Responding to User Interaction The Event Object

Abhijit Das
Abhijit Das
5,022 Points

Why my event.target isn't working?

ok please help me to find the issue, my html is

<input type="text">

my css is

.bg {
  background-color:#777;
  outline:none;
  border:solid 2px tomato;
}

and my js

const input = document.querySelector('input');
input.addEventListener('click', (e) => {
  if (e.target.tagName === 'INPUT') {
    input.className = "bg";
  } else {
    input.className = "";
  }   
});

once i click the input element the "bg" class name is adding, however, why it isn't removing, once i click on outside of input element? Sorry can't put the the code-pen link this time

1 Answer

ywang04
ywang04
6,735 Points

When you click on outside of input element, which will trigger a new event on other elements you clicked instead of input element itself. Therefore, the if else block won't be executed.

//won't be executed
if (e.target.tagName === 'INPUT') {
    input.className = "bg";
  } else {
    input.className = "";
  }   

To meet your requirement with event object, you can refer to the following codes:

const input = document.querySelector('input');

input.addEventListener('mouseover', (e) => {
  if (e.target.tagName === 'INPUT') {
    input.className = "bg";
  } 
});

input.addEventListener('mouseout', (e) => {
  if (e.target.tagName === 'INPUT') {
    input.className = "";
  }
});

or WITHOUT event object to meet your requirement :

const input = document.querySelector('input');

input.addEventListener('mouseover', () => {
    input.className = "bg";
});

input.addEventListener('mouseout', () => {
    input.className = "";
});