A
A
Anastasia2021-06-22 11:31:36
JavaScript
Anastasia, 2021-06-22 11:31:36

How to execute a function after a new element appears?

I have a function that is responsible for the animation for the input:

$(document).ready(function InputAnimation() {
  $(".form__exchange input").on("focusin", function () {
    $(this).addClass("active");
    $(this).parent().find("label").addClass("active");
  });

  $(".form__exchange input").on("focusout", function () {
    if (!this.value) {
      $(this).removeClass("active");
      $(this).parent().find("label").removeClass("active");
    }
  });
});


And there is a button, when pressed, the block in which this input is located is duplicated:

$(document).ready(function () {
  var cloneCount = 2;
  $(".form__add button").on("click", function () {
    $(".form__exchange:last").clone().insertAfter($(".form__exchange:last"));
    $(".form__exchange input:last")
      .attr("id", "exchange__code--" + cloneCount++)
      .attr("name", "exchange__code--" + (cloneCount - 1));
    $(".form__exchange label:last")
      .attr("for", "exchange__code--" + (cloneCount - 1))
      .text("Next #" + (cloneCount - 1) + ":");
  });
});


But if I duplicate this block, then the first function with animation does not work in the new input.
Please tell me how to fix this

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir, 2021-06-22
@Casufi

You hang up an event listener on a specific element, it works for you on it. In jQuery, as in bare javascript, there is a subscription function when you hang an event on a parent element and inside you check on which element it is called. You need to use it.
You hang the listener on the form, and you specify the input class where the selector is
60d1a11c71996735965986.png
. And in general, the 21st century is in the yard and all the code for adding the class can be replaced with pure css
https://developer.mozilla.org/en-US/docs/Web/CSS/: ...

P
pLavrenov, 2021-06-22
@pLavrenov

$('body').on('click','.myClickableElement',function(){
        ... event handler code ....
});

V
vItalIyIrtlach, 2021-06-22
@w13vitaliy

https://learn.javascript.ru/mutation-observer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question