Timmy Von Heiss
Timmy Von Heiss

Reputation: 2218

on click function does not work on elements appended with ajax

 $(document).on('turbolinks:load', function() {
    $('.box').on("click", function() {
      alert('hello')
    });
  });

This does not work on elements with class box that are appended with ajax. It only works on the elements that are present on the initial loading of the page. I have also tried as wrappers:

$(document).ready(function() { }); 

and

var helloscript = function() { };

but nothing works.

Upvotes: 0

Views: 169

Answers (2)

codenut
codenut

Reputation: 681

You may call it like:

$(document).on('click', '.box', function (event) {

});

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11472

Use correct event delegation for dinamically added elements:

 $(document).on('click', '.box', function() {
   alert('hello')
 });

You can read more about event delegation here.

Upvotes: 0

Related Questions