Search code examples
rails-3.1

Rails 3.1 loads scripts before the page is loaded. How to bind functions to page elements?


Putting this code in

$('#hello').click ->
  alert 'hello'

in posts.js.coffee in vanilla Rails 3.1 app does not work. The javascript is compiled and loaded before the page so the function isn't bound to its element. There are easy solutions, like manually loading the js on the page rather than using the asset pipeline, or using JQuery .live functions, but it seems like this code should work out of the box. Am I missing something??


Solution

  • I might be pointing out the obvious here, but have you (in jQuery) tried this:

    $(function(){    
        //your code
        $('#hello').click(function(){
        alert("hello");
        });
    });
    

    or

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

    These (atleast under normal circumstances) should prevent any javascript inside from doing anything until the DOM has been loaded.

    Hope this helps