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.
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");
}
});
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);
}
});
});
}
if your browser compatibility requirements support it... MutationObserver might be a good candidate here
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
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/
Related
I have a specific effect I want for a website I'm building. As you can see in this website, I want the screen to "snap to" the next section after the user scrolls, but only after (not the instant) the scroll event has fired. The reason I don't want to use a plugin like panelSnap is because I
1: Want smaller code and
2. Want the website, when viewed on mobile, to have more of the "instant snap" effect (try reducing the browser size in the website mentioned above). I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that... :(
So all of that said, here's the code:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed);
}
$(window).scroll(function() {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
});
});
My problem is that every time the snap function is called, it triggers the scroll event, which throws it into a loop where the window won't stop scrolling between the first and second elements. Here's the poor, dysfunctional site: https://tcfchurch.herokuapp.com/index.html Thank for the help.
You can use a boolean to record when the scroll animation in snap is in progress and prevent your $(window).scroll() event handler from taking any action.
Here's a working example:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var scrollInProgress = false;
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
scrollInProgress = true;
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed, 'swing', function() {
// this function is invoked when the scroll animate is complete
scrollInProgress = false;
});
}
$(window).scroll(function() {
if (scrollInProgress == false) {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
}
});
});
The variable scrollInProgress is set to false by default. It is then set to true when the scroll animate starts. When the animate finishes, scrollInProgress is set back to false. A simple if statement at the top of your $(window).scroll() event handler prevents the handler from taking any action while the animate scroll is in progress.
Have you considered using the well known fullPage.js library for that? Check out this normal scroll example. The snap timeout is configurable through the option fitToSectionDelay.
And nothing to worry about the size... it is 7Kb Gzipped!
I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that
fullPage.js also provides responsiveWidth and responsiveHeight options to turn it off under certain dimensions.
Click on the second div and see how it stutters.
Demo: http://jsfiddle.net/mirohristov/76xtt3hm/
$("body").on('click', '.mysection', function(){
var el = $(this);
if($(this).hasClass('active')){
url = $('.active .nectar-button').attr('href');
window.open(url, '_self')
}else{
$("html, body").animate({ scrollTop: el.offset().top+'px' }, 500,function(){
el.addClass('active');
var scroller = setInterval(function(){
$("html, body").scrollTop(el.offset().top);
}, 50); //if i change this to 14 or 1 it works here but in my real case there is more content and images in the divs and it's like 150 here - it's sluggish or flickers
$('.mysection').not(el).removeClass('active');
setTimeout(function(){window.clearInterval(scroller)}, 1000);
});
}
});
In the real project, I'm using divs as pages to display content. The selected div should aligned with top of page while the div above is being 'closed'.
I used a loop to re-set the scrollTop to that of the element position but in my real example it, even though the setTitmeout delay is 14 or 1, it acts like in the demo (at 50 delay).
I belive it's because there's more content and full-width, HD background images that go fullscreen in my actual project. It's as if the setTimeout is updated slower than the CSS animation.
How can I make it smooth? Is it even possible?
Try this (demo)
$('body').on('click', '.mysection', function () {
var scroller,
el = $(this),
html = $('html')[0],
body = $('body')[0];
if ($(this).hasClass('active')) {
url = $('.active .nectar-button').attr('href');
window.open(url, '_self')
} else {
el.one('transitionend', function (e) {
clearInterval(scroller);
});
$('html, body').animate({
scrollTop: el.offset().top + 'px'
}, 500, function () {
el.addClass('active');
scroller = setInterval(function () {
var top = el.offset().top;
html.scrollTop = top;
body.scrollTop = top;
}, 10);
$('.mysection').not(el).removeClass('active');
});
}
});
I found a solution that didn't work mainly that I want. Here it is:
topic url
and this solution works for me:
if(pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top)
{
$('#date').html($(this).find('.description').text());
return;
}
jsfiddle
but I want to change content description in gray box more smooth. I've tried to give animation in CSS for it, but it didn't work.
I modified your script a bit to detect when the text changes and when that happens I apply a small animation with jQuery. I set the opacity to a low value, e.g. opacity:0.4 and then make a quick animation back to opacity:1.
This will help your user to see easier the change in the text.
$(window).load(function () {
$(window).on('scroll resize', function () {
var pos = $('#date').offset();
$('.post').each(function () {
if (pos.top >= $(this).offset().top && pos.top <= $(this).next().offset().top) {
var newDescr = $(this).find('.description').text();
var oldDescr = $('#date').html();
$('#date').html(newDescr);
if(newDescr !== oldDescr) {
$('#date').css('opacity', 0.4).animate({ 'opacity': '1',}, 200);
return;
}
}
});
});
$(document).ready(function () {
$(window).trigger('scroll'); // init the value
});
});
Demo here
I'm trying to make a simple jQuery plugin that will scroll page down until it reaches special div like a #stopscroll. I got a simple jQuery plugin to stop scroll on special size:
$(window).scroll(checkscroll);
function checkscroll(){
var top = $(window).scrollTop();
if(top > 300){
$('#share_box').fadeOut('slow');
}else{
$('#share_box').fadeIn('slow');
}
}
checkscroll();
How do I make it scroll to a special div instead of scrolling a specified size? I want it to stop scrolling when div #sharebox reach #stopscroll.
I don't know if I understand your question correct but I think I had the same problem a while back. I fixed it like this:
$(document).ready(function() {
/** HIDE MENU **/
$(".menu").css("margin-top", "-88px");
var mustSlideDown = true;
var mustSlideUp = false;
$(window).scroll(function() {
var verschil = ($(window).scrollTop() / 5);
if (verschil > 40 && mustSlideDown) {
$('.menu').animate({'margin-top': '0px' }, {duration: 500, queue: false});
mustSlideDown = false;
mustSlideUp = true;
}
else if (verschil < 40 && mustSlideUp) {
$('.menu').animate({'margin-top': '-88px' }, {duration: 500, queue: false});
mustSlideUp = false;
mustSlideDown = true;
}
});
});
Didn't get much of your English, but maybe you are looking for this-
Window.location='#scollDiv';
I run the following code on a page (#home) that should smoothly inject a slider or if the page container is under 480px leave the page as is.
I cannot get the resize event to work 100% smoothly.
If I reduce the window the script (js.slide.js) wont get triggered but the content will be loaded in (slide.php). If I continue to reduce the window a little extra it will all work ok.
Could anyone please advise as to how I could get this working smoothly. The code is as follows
$(document).ready(function(){
if ($("#home").length > 0 ){
var homeSlideShow = {
$promoArea: $('#promo-area'),
$currentContent: $('#promo-area').contents(),
$pageContainer: $('.page'),
init: function(){
var hSS = homeSlideShow;
if (hSS.$pageContainer.width() > 480 ){
hSS.setTheSlideShow();
} else{
hSS.$promoArea.html(hSS.$currentContent);
}
},
setTheSlideShow: function(){
var hSS = homeSlideShow;
$.getScript(myscript_wp_vars.temp_dir + '/js/slide.js', function(){
hSS.$promoArea.load(myscript_wp_vars.temp_dir + '/libs/slide.php #c4u-slide',
function(){
var options = {
preloader: false,
nextButton: true,
prevButton: true,
animateStartingFrameIn: true,
transitionThreshold: 250
};
var sequence = $("#sequence").sequence(options).data("sequence"),
$slideShow = $("#c4u-slide");
});
});
}
};
//
// Check page size
//
if (homeSlideShow.$pageContainer.width() > 480 ){
homeSlideShow.setTheSlideShow();
}
//
// On window resize
//
$(window).resize(function() {
homeSlideShow.init();
});
}// END home.length
});//End $(document).ready(function()
Thanks in advance for any assistance or advice.
Cheers
Noel
window.resize event is triggered multiple times, depending of browser's behaviour. I'll suggest you to try this:
var timeoutResize;
$(window).resize(function(){
if(typeof timeoutResize != 'undefined') clearTimeout(timeoutResize);
timeoutResize = setTimeout(function(){homeSlideShow.init();},50);
});