Frage

Here is a JSFiddle for the problem.

When a user scrolls to the chart and it is visible in the window, the chart appears with the animation. However, when a user scrolls back up and then scrolls down again, the chart reappears and doubles in size.

I would like the chart to stay fixed as it is, once it has appeared the first time a user scrolls to it.

Here is the code:

var data = [{
    value: 30,
    color: "#F38630"
}, {
    value: 50,
    color: "#E0E4CC"
}, {
    value: 100,
    color: "#69D2E7"
}];

var inView = false;

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemTop <= docViewBottom) && (elemBottom >= docViewTop));
}

$(window).scroll(function() {
    if (isScrolledIntoView('#canvas')) {
        if (inView) { return; }
        inView = true;
        new Chart(document.getElementById("canvas").getContext("2d")).Pie(data);
    } else {
        inView = false;  
    }
});
War es hilfreich?

Lösung

Besides the doubling in size, which I can't reproduce, you're resetting the inView variable each time the graph is scrolled out of view. When it's back in view again, you're creating a new graph. This happens every time.

The solution is to not set inView back to false once the graph has been rendered once:

var graphRendered = false;
...
$(window).scroll(function() {
  if (! graphRendered && isScrolledIntoView('#canvas')) {
    graphRendered = true;
    new Chart(document.getElementById("canvas").getContext("2d")).Pie(data);
  }
});

(renamed inView to graphRendered to better suit what it's being used for)

fiddle

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top