0

i am trying to figure out why every time an event is fired, the last element is the one that's shown in the console in the event function, regardless of which element fires the event.

There is a login form which only contains username input and password, i gather their elements on Javascript from getElementsByTagName and do an iteration over items to set the events and do whatever logic i need to do on the element that's firing the event.

HTML

<form>
    <div class="input-field">
        <label for="username">"Username"</label>
        <input class="validate" id="username" type="text">
    </div>
    <div class="input-field">
        <label for="password">"Password"</label>
        <input class="validate" id="password" type="text">
    </div>
</form>

Javascript

document.onload = init();

function init(){
    var inputFields = document.getElementsByClassName("input-field");

    setFloatingLabel(inputFields);
}

function setFloatingLabel(inputFields){
    for(i = 0; i < inputFields.length; i++){
        var field = inputFields.item(i),
            input = field.getElementsByTagName("input").item(0);

        input.addEventListener("focus", () => {
            console.log(input);
            // field.classList.add("input-focus");
        });

        input.addEventListener("blur", () => {
            console.log(input);
            // field.classList.remove("input-focus");
        });
    }
}

the console always shows the last input.. which is #password, why does this happen?

Ashish Bahl
  • 1,482
  • 1
  • 18
  • 27
Oscar Reyes
  • 4,223
  • 8
  • 41
  • 75

0 Answers0