Search code examples
ruby-on-railscoffeescriptturbolinks

Rails Coffeescript not executing properly at page load


I have a nav-bar menu that is displayed in traditional horizontal nav bar format. With small screen sizes I would like to use coffeescript to remove the nav element with the links and append it to a dropdown menu activated by clicking on a hamburger link.

The trouble Im having is that the above action isnt always executing only about 30% of the time. This makes me wonder if its Turbolinks or my profound noobishness with coffeescript? The code is below. Am I doing this right?

(.small) is my CSS class hidden at greater than 768 with a media query

ready = ->  

    $( window ).resize(menuAdjust)


    $('.hamburger').click ->
        $('#hidden').toggle(  )


menuAdjust = ->
 if ($(".small").css("display") == "block")
     $('#menu').appendTo('#hidden');
 else
     $('#menu').appendTo('#main')

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

Solution

  • Your CoffeeScript code will only trigger menuAdjust when a user resizes the browser window because you have only registered menuAdjust with the ready() callback and not the 'page:load' event as well. E.g menuAdjust will only be triggered on a full page refresh and not a Turbolinks page load. Register menuAdjust to also execute on the Turbolinks page load event:

    $(document).on('page:load', menuAdjust)
    

    You can also temporarily disable Turbolinks to be certain this is the cause of the issue.