JavaScript catch onfocus event

763 Views Asked by At

I have some inputs and a button. I want to implement function which allows to delete one of recently focused/focused out input.

I set onfocusout function which sets a click listener on button. If I focus on first input then focus out from it and click on button - works fine. But when I focus on first input, then on second and click on button - i get deleteCell() function performed n times i focused out.

How to let it remember only last onfocusout event? It seems to count my onfocusout events before clicking on button.

Thank you.

var input = document.createElement("input");
input.setAttribute("onfocusout", "myFunction()");

function myFunction() {
    document.getElementById("delete-cell").addEventListener("click", function () {
        deleteCell();
    });
}

function deleteCell() {
    alert(1);
}
1

There are 1 best solutions below

3
Greg Brodzik On

Try adding an on-focusout listener to the relevant class of elements, and then add a "to-delete" class for the element focusedout (using "this" property). But only add this "to-delete" class after you have first removed it from all elements. This should keep you dialed into the element related to the most recent focusout event.

 $(".element-class").on("focusout", function() {
     $(".element-class").removeClass("to-delete");
     $(this).addClass("to-delete");
 })

Then simply write a function that will delete the element with the "to-delete" class, triggered by an on-click event.

Here is fiddle: https://jsfiddle.net/gbrodzik/ej4czqrc/6/