Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Run Script only if a div is in the viewport

Posted on 2016-11-05
6
Medium Priority
?
100 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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 59

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 59

Expert Comment

by:Julian Hansen
ID: 41878224
You are welcome
0

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

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

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
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)
Suggested Courses

670 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