Solved

Run Script only if a div is in the viewport

Posted on 2016-11-05
6
65 Views
Last Modified: 2016-11-07
I need to run a script only if it is in the viewport.  The following runs it to early cause the divs I need to see are still below the fold so the animation plays before you can see it.  How do I fire a script only if the div is in the viewport?
 $ =  jQuery
            $(window).on('scroll', function(){

                  if($('.imgs').hasClass('animated-in')){

                    $('#paichart1').pieChart({
                        barColor: '#ED1C23',
                        trackColor: '#DFE0E0',
                        lineCap: 'butt',
                        lineWidth: 20,
                        onStep: function (from, to, percent) {
                            $(this.element).find('.pie-value').text(Math.round(percent) + '%');
                        }
                    });

                    $('#paichart2').pieChart({
                        barColor: '#ED1C23',
                        trackColor: '#DFE0E0',
                        lineCap: 'butt',
                        lineWidth: 20,
                        onStep: function (from, to, percent) {
                            $(this.element).find('.pie-value').text(Math.round(percent) + '%');
                        }
                    });
                    
                    $('.imgs').removeClass('animated-in animated hidde_data');
                }
            })
            

Open in new window

0
Comment
Question by:rgranlund
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
6 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 41875728
Using this plugin : https://github.com/customd/jquery-visible

 if($("#yourDivID").visible()) {

Open in new window


(function($){

    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function(partial,hidden,direction){

        if (this.length < 1)
            return;

        var $t        = this.length > 1 ? this.eq(0) : this,
            t         = $t.get(0),
            vpWidth   = $w.width(),
            vpHeight  = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function'){

            // Use this native browser method, if available.
            var rec = t.getBoundingClientRect(),
                tViz = rec.top    >= 0 && rec.top    <  vpHeight,
                bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
                lViz = rec.left   >= 0 && rec.left   <  vpWidth,
                rViz = rec.right  >  0 && rec.right  <= vpWidth,
                vVisible   = partial ? tViz || bViz : tViz && bViz,
                hVisible   = partial ? lViz || rViz : lViz && rViz;

            if(direction === 'both')
                return clientSize && vVisible && hVisible;
            else if(direction === 'vertical')
                return clientSize && vVisible;
            else if(direction === 'horizontal')
                return clientSize && hVisible;
        } else {

            var viewTop         = $w.scrollTop(),
                viewBottom      = viewTop + vpHeight,
                viewLeft        = $w.scrollLeft(),
                viewRight       = viewLeft + vpWidth,
                offset          = $t.offset(),
                _top            = offset.top,
                _bottom         = _top + $t.height(),
                _left           = offset.left,
                _right          = _left + $t.width(),
                compareTop      = partial === true ? _bottom : _top,
                compareBottom   = partial === true ? _top : _bottom,
                compareLeft     = partial === true ? _right : _left,
                compareRight    = partial === true ? _left : _right;

            if(direction === 'both')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
            else if(direction === 'vertical')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
            else if(direction === 'horizontal')
                return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
        }
    };

})(jQuery);

Open in new window

0
 
LVL 7

Author Comment

by:rgranlund
ID: 41875732
Is that script the plugin?  If so Can I place it directly on the page or do I need to include it?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41875789
Best is to download it and include it so in your page
0
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 
LVL 56

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41875898
A simple implementation - activates animation once after target element scrolls into view
<script>
var done = false;
$(function() {
	$(window).scroll(function() {
		if (done) return;
		t = $('.target');
		offset = t.offset();
		st = $(window).scrollTop();
		wh = $(window).height();
		if (st > offset.top - wh + t.height()) {
			doAnimate();
			done = true;
		}
	});
});
</script>

Open in new window

Working sample here
0
 
LVL 7

Author Closing Comment

by:rgranlund
ID: 41877639
Thanks
0
 
LVL 56

Expert Comment

by:Julian Hansen
ID: 41878224
You are welcome
0

Featured Post

Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question