1

I am unsure why this is happening, but I created a scrolling visualization (https://jhjanicki.github.io/hongmutrade_v2/) where the text should sync up with the visuals, more specifically for the second half of the visualization, the force graph should be synced with "Are Hongmu Species Protected?" and the China map should be synced with "Demand and Transit Countries", etc.

I assign a class "section" to the text where I want a particular viz to appear. And I store these heights into an array as the following: (From Trigger event when user scroll to specific element - with jQuery)

  var topArray = [];
  $(".section").each(function () {
        var hT = $(this).offset().top;
        var hH = $(this).outerHeight();
        var wH = $(window).height();
        topArray.push(hT+hH-wH);
  });

And when the user scrolls to a target then it triggers certain visualizations to appear.

if (scrollTop > topArray[1]){
             d3.selectAll(".stat2")
                    .transition()
                    .duration(100)
                    .style('opacity',0);
             d3.selectAll(".stat3")
                    .transition()
                    .duration(100)
                    .style('opacity',1);

       }else{
            d3.selectAll(".stat3")
                    .transition()
                    .duration(100)
                    .style('opacity',0);

       }

When I create a branch gh-pages on github, the first time I load it the visualizations are out of sync, they move forward too quickly, but if I click refresh then they sync up. I am pretty confused why this is happening.
And I already tested it on two different computers each with two different browsers (Chrome and Firefox). It also has the same problem locally.

Any help would be appreciated

For example, if I add this code to force the page to reload once then it works:

window.onload = function(){
  if(!window.location.hash){
   window.location = window.location + '#loaded';
   window.location.reload();
  }
} 
jhjanicki
  • 425
  • 1
  • 3
  • 11

1 Answers1

2

Your script is executing before the DOM is fully loaded, hence the measures like $(window).height() or window.innerHeight are incorrect.

The reason why the code works on page reloads is that when you reload the page, the resources like styles and web fonts are already available in your browser's cache, hence the page's DOM is already fully loaded when the script runs.

Solution:

Wrap your script (the one at the bottom of index.html) inside a jQuery ready function's callback

$(function() {
// move code here
})

Also, move all the <script> outside of <head>, and put them just above your script.

Mehdi
  • 7,204
  • 1
  • 32
  • 44