Tom Nolan
Tom Nolan

Reputation: 1957

How to only run a script if the DIV is in view?

I have a script that I wrote:

jQuery(function($) {
        $('.count').countTo({
            from: 0,
            to: '400',
            speed: '3000',
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });

I need that script only to run when the container div is visible.

<div class="container">
   <div class="count"></div>
</div>

To clarify, the div will always be visible, but when the user scrolls it in to view. Any ideas?

http://www.windycitydigital.net/iconvert/ - Example, at the bottom of the page those counters automatically start. I don't want that script to initiate until the user scrolls into view of them.

Upvotes: 1

Views: 2951

Answers (4)

Razor
Razor

Reputation: 720

Here is an example with the alert activated only when the #mydiv is in view: This works as you asked. Make sure the window is small so #midiv is not in view from the beginning. And after you scroll down, after the entire #mydiv is visible it will activate the alert from the scroll event.

http://jsfiddle.net/u3eCG/7/

divScroll = $("#mydiv").offset().top + $("#mydiv").height();

$(window).scroll(function(){
   lastLineScroll = $("body").scrollTop() + $(window).height();
   if (divScroll < lastLineScroll)  {
                     alert("Div is visible");
                     $(window).unbind("scroll");
   }
});

Upvotes: 1

Nathaniel Currier
Nathaniel Currier

Reputation: 344

you could do something like this..

function isViewed(selector) {

    var viewport = $(window),
        item = $(selector);

    var viewTop = viewport.scrollTop(),
        viewBtm = viewport.scrollTop() + viewport.height(),
        itemTop = item.offset().top,
        itemBtm = item.offset().top + item.height();

    return ((itemTop < viewBtm) && (itemTop > viewTop));
};

var counter = setInterval(function() {countdown()}, 500);

var countdown = function() {
    console.log('are you there?');
    if(isViewed('#mydiv')) {
        clearInterval(counter);    
        console.log('yes i am here.'); // call countdown here 
    }
};

here is a jsfiddle to demonstrate http://jsfiddle.net/pixelchemist/aLT7w/

Upvotes: 0

Nathaniel Currier
Nathaniel Currier

Reputation: 344

if your browser compatibility requirements support it... MutationObserver might be a good candidate here

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Upvotes: 0

vborutenko
vborutenko

Reputation: 4443

What code shoud hide/show div?For example you can use this code to show div

$('.container').show(0, onContainerVisible);

function onContainerVisible(){
 jQuery(function($) {
    $('.count').countTo({
        from: 0,
        to: '400',
        speed: '3000',
        refreshInterval: 50,
        onComplete: function(value) {
            console.debug(this);
        }
    });
});
}

Upvotes: 0

Related Questions