R
R
Robert2015-08-17 15:00:36
JavaScript
Robert, 2015-08-17 15:00:36

Why does the js script not work after adding the news?

The point is this.
It is possible to add news via ajax, after which the create action renders the create.js.erb file accordingly. He, in turn, is engaged in adding a new block. Everything is simple and everything works.
I have a custom js file in which I described some actions for each news on the page. By clicking on the corresponding block with the class "show-form" I show the form for editing the news, on the block that we just clicked. Everything works here too, here is the code:

var show = function() {
  $('.show-form').click(function(){
    var id = $(this).attr("data-id");
    $(".edit-form[data-id =" + id + "]").toggle('fast');
  });
}

$(document).ready(show);
$(document).on('page:load', show);

The problem is that this script doesn't work after adding the news itself via ajax. You have to reload the page and only then everything starts working.
How to force the script to be loaded again after adding the news?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Inchin ☢, 2015-08-17
@Jowan

Of course, it does not work - there are no handlers.

//Перебираются все элементы с данным селектором и им устанавливается обработчик. 
//Соответственно, если элемент загрузится позже, он будет без обработчика
 $('.show-form').click(function(){});

//Отлавливается просто клик на странице, 
//если целевой элемент удовлетворяет селектору, вызывается обработчик.
$(document).on("click", ".show-form", function(){});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question