Search code examples
jqueryturbolinks

Rails 4 / Turbolinks / jQuery: keydown event not being triggered on newly inserted element?


I'm on Rails 4 using the jquery-turbolinks gem. I have a link that when clicked, will add a input field to the DOM using jQuery:

$(".add_color").html("<input id='add_color_text_field' type='text' name='color' placeholder='Provide a color name'>");

However, the jQuery in my application.js is not firing for this newly generated input:

    $(function() {


        $('#add_color_text_field').keydown(function(e) {
            alert("here");
        });

       ...

This works when I change the selector to point an already existing input field on the initial page load, so I'm sure it works. What do I need to change to my jQuery to make my newly generated DOM element works with turbolinks?


Solution

  • You may want to use the jquery-turbolinks gem. It is easily installed:

    Gemfile:

    gem 'jquery-turbolinks'
    

    run bundle install and edit the Javascript manifest:

    //= require jquery
    //= require jquery.turbolinks
    //
    // ... your other scripts here ...
    

    and should solve your problem.

    Please read the note on binding to $(document) at the end of the github page (do not bind inside $(function () {...}); as those events will be executed multiple times then).