0

I am trying to use the focus event to get red background when the element (first name or last name) is focused, and to get white background when the element in not focused. However, the code does not work. Any advice to make it work will be highly appreciated.

Edit section: I read the suggestions in the following URL: Getting the ID of the element that fired an event I tried the suggested solutions but they did not work for me. I have to elements" "fname" and "lname" and I want both of them to use the same function. I am failing to pass to the function the Id of the element.

Thank you, SL

document.getElementById("fname").addEventListener("focus", focus_function);
document.getElementById("fname").addEventListener("focusout", focusout_function);

document.getElementById("lname").addEventListener("focus", focus_function);
document.getElementById("lname").addEventListener("focusout", focusout_function);

function focus_function(event) {
  var x = event.target.id;
  document.getElementById(x).style.backgroundColor = "red";
}

function focusout_function(event) {
  var x = event.target.id;
  document.getElementById(x).style.backgroundColor = "white";
}
<p>This example uses the addEventListener() method to attach a "focus" event (red background) and "focusout" event (white background) to two input elements.</p>

Enter your first name: <input type="text" id="fname"><br> Enter your last name: <input type="text" id="lname">
Nick
  • 138,499
  • 22
  • 57
  • 95
  • `document.getElementById("fname").addEventListener("focus", focus_function);` etc. – Nick Aug 29 '22 at 23:59
  • I have to elements Ids: "fname" and "lname". I want both of them to use the same function. I am failing to pass to the function the Id of the element. – user19874655 Aug 30 '22 at 00:34
  • The `event` parameter to the function is passed automatically. You don't need to do anything to make that happen. – Nick Aug 30 '22 at 00:36
  • Thank you very much, Nick. It still does not work. Can you please take a look at the function? function focus_function(event) { var x=event.target.id document.getElementById(x).style.backgroundColor = "red"; } – user19874655 Aug 30 '22 at 01:43
  • I've converted your code to a snippet and if you run it you can see that it works fine with the changes suggested. – Nick Aug 30 '22 at 01:47

0 Answers0