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">