Home > Mobile >  When you leave input field, a function is triggered which change input background color
When you leave input field, a function is triggered which change input background color

Time:04-06

How can I do like, when my cursor leave input field, a function is triggered which change input background color. I was trying to do like this, but did not work well.

<!DOCTYPE html>
<html>
<body>

Enter your name: <input type="text" id="name" onchange="changeColor()">

<script>
function changeColor() {
  const x = document.getElementById("name");
  x.style.background = "red";
}
</script>

</body>
</html>

CodePudding user response:

It seams that you looking for onfocusout event.

function changeColor(ev) {  
  if (ev.value.length > 0) {
    ev.style.background = "red";  
  }
}
Enter your name: <input type="text" id="name" onfocusout="changeColor(this)">

CodePudding user response:

function changeColor(ev) {
  ev.target.style.backgroundColor = "red";
}

CodePudding user response:

You can use the blur event to target specifically the lose of focus:

Enter your name: <input type="text" id="name">

<script>
const x = document.getElementById("name");

x.onblur = changeColor;

function changeColor() {
  x.style.background = "red";
}
</script>

CodePudding user response:

Try the onm ouseleave event listener. onchange usually involved the value of the input field changing.

In CSS you have :focus selector to style based of if the input is focused or not

  • Related