最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Run a script when the element is in view - Stack Overflow

programmeradmin0浏览0评论

Can someone fix this script so it runs when the element is in the view. In other words, it needs to wait until it's visible to run. Thanks! -Dan

$('.amount-chart').each(function(){
var $chart = $(this),
  size = parseFloat( $chart.outerWidth() ),
  clearSet;

$chart.css({
  height: size
})
.easyPieChart({
    size: size,
    animate: 2000,
            onStep: function(from, to, currentValue) {
                $(this.el).find('span.amount-counter').text(Math.round(currentValue));
            }
});

$(window).on('resize', function(){

   size = parseFloat( $chart.outerWidth() );

   $chart.css({
      height: size
   });

   //clearTimeout(clearSet);
   //clearSet = setTimeout(function(){
      $chart.removeData('easyPieChart').find('canvas').remove();
      $chart.easyPieChart({
         size: size,
         animate: 1
      });
   //}, 100);
});    

});

Can someone fix this script so it runs when the element is in the view. In other words, it needs to wait until it's visible to run. Thanks! -Dan

$('.amount-chart').each(function(){
var $chart = $(this),
  size = parseFloat( $chart.outerWidth() ),
  clearSet;

$chart.css({
  height: size
})
.easyPieChart({
    size: size,
    animate: 2000,
            onStep: function(from, to, currentValue) {
                $(this.el).find('span.amount-counter').text(Math.round(currentValue));
            }
});

$(window).on('resize', function(){

   size = parseFloat( $chart.outerWidth() );

   $chart.css({
      height: size
   });

   //clearTimeout(clearSet);
   //clearSet = setTimeout(function(){
      $chart.removeData('easyPieChart').find('canvas').remove();
      $chart.easyPieChart({
         size: size,
         animate: 1
      });
   //}, 100);
});    

});

Share Improve this question asked Dec 14, 2016 at 18:36 user2636033user2636033 231 silver badge6 bronze badges 3
  • Put it to playcode.io. Where your element not visible? – Alex Shtorov Commented Dec 14, 2016 at 18:43
  • Hi Alex, I got the playcode.io to work ... true.playcode.io ... playcode.io/true – user2636033 Commented Dec 14, 2016 at 19:24
  • My answer solve your problem? – Alex Shtorov Commented Dec 14, 2016 at 20:19
Add a ment  | 

1 Answer 1

Reset to default 6

Thank you for full description! Look at demo

HTML

<div id="el">Pie Chart</div>    

JavaScript

var inited = false
function init() {
   // init your chart
   // code here run once on element with id="el" will in viewport
}

$(window).on('scroll', function() {
  if ( inited ) {
    return
  }

  if ( el.offsetTop >= window.innerHeight + document.body.scrollTop ) {
    inited = true
    init()
  }
})
发布评论

评论列表(0)

  1. 暂无评论