简体   繁体   中英

HTML elements disappear when navigating to the page, re-appear on page refresh

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM