E
E
Eugene2019-03-07 17:36:26
JavaScript
Eugene, 2019-03-07 17:36:26

Plugin event not firing when element is added after page load?

This question is not related to Bootstrap TouchSpin in any way , but the example is made on it, I think the same situation will be with another plugin.

Essence of the question:
There is a page with elements (in our case, it is a Bootstrap TouchSpin spinner), some of them are in the code when the page is loaded, and some are loaded by ajax depending on the content. The situation is that events for changes (any events) do not respond to elements added after the page is loaded.
Approximate example (working example: https://jsfiddle.net/atach/s210gr6y/18/ ):

// Инициализирутся элементы которые на странице
initSpinner();

setTimeout(function() {
  // При какиих то условиях подгружаются и иногда добавляются еще
  $(".newSpinner").html('<hr/><input class="spinner" value="1" readonly /><br/>');
       // Повторно инициализирую спиннер
      initSpinner();
}, 500);

$(".spinner").on("touchspin.on.stopspin", function(target) {
  alert("On change")
});

function initSpinner() {
  $("input.spinner").trigger('touchspin.destroy');
  $("input.spinner").TouchSpin();
}
With this code, the Change event does not fall on new elements.

If I re-listen to events, then for already previously initialized ones, they fire several times (Working example: https://jsfiddle.net/atach/s210gr6y/19/ )
$(".spinner").on("touchspin.on.stopspin", function(target) {
    alert("On change")
  });


Tell me how to be right, is it possible to somehow reset the previously called event, so that it would not be listened to.
Tried both through .one and .off - it doesn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Kirenkov, 2019-03-07
@atachrus

$("body").on("touchspin.on.stopspin", ".spinner", function(target) {
    alert("On change")
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question