Search code examples
ajaxruby-on-rails-5turbolinks

Rails Turbolinks - remove style before caching


I have this div:

<div class="hidden" id="more-items">

that I unhide/hide if click event happens:

<button type="button" onclick="showHide()">

Via:

@showHide = () ->
  $('div#more-items').toggleClass('hidden')
return

But problem is that div supposed to be closed after user comes back to the page. If he leaves it open, it remains open for 1 or 2 seconds after content loaded. Not sure at what stage it closes.

This doesn't help:

document.addEventListener 'turbolinks:before-cache', (e) ->
  $('div#more-items')[0].style.display = 'none'
return

as well as this:

document.addEventListener 'turbolinks:before-render', (e) ->
  e.data.newBody.getElementById('more-items').style.display = 'none'
return

Solution

  • I think the issue is with the indentation of the returns. The Rails asset pipeline wraps each coffeescript file in an immediately invoked function expression (IIFE), so your compiled JavaScript would look like:

    (function() {
      this.showHide = function() {
        return $('div#more-items').toggleClass('hidden');
      };
    
      return;
    
      document.addEventListener('turbolinks:before-cache', function(e) {
        return $('div#more-items')[0].style.display = 'none';
      });
    
      return;
    
    }).call(this);
    

    The outer function will return early and your turbolinks:before-cache code will never get run. CoffeeScript automatically returns the last line. If you want to return undefined, make sure your return is indented at the same level as your function's code.

    Changing your coffeescript to the following should fix this:

    @showHide = () ->
      $('div#more-items').toggleClass('hidden')
    
    document.addEventListener 'turbolinks:before-cache', (e) ->
      $('div#more-items')[0].style.display = 'none'
    

    To tidy things up a bit, you could do also the following:

    HTML:

    <button type="button" id="toggle-more">
    

    CoffeeScript:

    $(document).on 'click', '#toggle-more', ->
      $('#more-items').toggleClass('hidden')
    
    $(document).on 'turbolinks:before-cache', ->
      $('#more-items').addClass('hidden')