Solved

Run Script only if a div is in the viewport

Posted on 2016-11-05
6
50 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
  • 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 54

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 54

Expert Comment

by:Julian Hansen
ID: 41878224
You are welcome
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn how to dynamically set the form action using jQuery.
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…

810 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