Solved

Run Script only if a div is in the viewport

Posted on 2016-11-05
6
28 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
Comment Utility
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
Comment Utility
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
Comment Utility
Best is to download it and include it so in your page
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
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
Comment Utility
Thanks
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
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 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…

771 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now