0

Using Ruby on Rails for my framework. I have written code to create a chessboard. My HTML elements that I have being created by JavaScript disappear when I first navigate to the page with the containing div that I have the elements being appended to. The chessboard is visible for a split second and then disappears when first navigating to the page, but refreshing makes the chessboard appear and stay. This is my JavaScript file:

    $(function() {
      var $boardContainer = document.querySelector('.board-container'); //grabs the div added to the index page -JB
      var $table = document.createElement("table"); 

      function buildBoard() {

        for (var i = 0; i < 8; i++) {   
            var $tr = document.createElement('tr');
            for (var n = 0; n < 8; n++) {
                var $td = document.createElement('td');
                $td.setAttribute('data-coord', i+','+n) //grabs the row iterator (i) and the cell iterator (n) and uses them for the coords! -JB
                if (i%2 == n%2) {           //every even square is white, odd is black -JB
                    $td.className = "white";
                } else {
                    $td.className = "black";
                }
                $tr.appendChild($td);
            }
            $table.appendChild($tr);
        }
        $boardContainer.appendChild($table);
      }
      buildBoard();
    });

And this is the element that the elements append to:

<%= link_to 'Home', root_path, class: 'btn btn-primary'%>

<div class="board-container d-flex justify-content-center">



</div>

Wanting to figure out why the chessboard doesn't stay rendered on initial page load, but will stay when refreshed.

Josh Bangle
  • 251
  • 3
  • 16

1 Answers1

1

Sounds like Turbolinks is causing this, instead of doing $(function() { .. } which is the equivalent to $(document).ready(function() { .. }) (L1), you should do:

$(document).on('turbolinks:load', function() {

  // your code here

})

Here's the Turbolinks repo for your reference: https://github.com/turbolinks/turbolinks

L1: What does $(function() {} ); do?

Gotenks-J
  • 79
  • 1
  • 5
  • 1
    This was exactly the issue, thank you! I'll check out what other issues turbolinks can cause like this as well. – Josh Bangle Nov 13 '19 at 22:07