Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Run Script only if a div is in the viewport

Posted on 2016-11-05
6
Medium Priority
?
120 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 60

Accepted Solution

by:
Julian Hansen earned 2000 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 60

Expert Comment

by:Julian Hansen
ID: 41878224
You are welcome
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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…
Suggested Courses

971 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