jQuery auto scroll div to div and back to top - javascript

I found this code for autoscroll a page.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function () {
var myInterval = false;
myInterval = setInterval(AutoScroll, 5000);
function AutoScroll() {
var iScroll = $(window).scrollTop();
iScroll = iScroll + 500;
$('html, body').animate({
scrollTop: iScroll
}, 1000);
}
$(window).scroll(function () {
var iScroll = $(window).scrollTop();
if (iScroll == 0) {
myInterval = setInterval(AutoScroll, 5000);
}
if (iScroll + $(window).height() == $(document).height()) {
clearInterval(myInterval);
setTimeout(function(){ window.location.href = "index.php"; },3000)
}
});
});
});//]]>
</script>
My page looks like this:
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5"></div>
My goal is to autoscroll from div to div after 20 seconds en after the last div back to top.
My Question is:
How to make it work scrolling from div to div?
I use window.location.href = "index.php" for refreshing the page en start over again. Is there a different way to achieve the same without a refresh? So go back to the top div and refresh the content of the page?

To scroll from div to div, you could define an array of the selectors for each div. Then in your AutoScroll function, get the element at the current index, get the offset from the top of the page for that element, and scroll to that. Then increment the index value.
To scroll to the top of the page, set the index back to 0 when there are no more elements to scroll to
Something like this should work:
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function () {
var myInterval = false;
var index = 0;
var elements = ["#div1","#div2","#div3","#div4","#div5"];
myInterval = setInterval(AutoScroll, 5000);
function AutoScroll() {
$('html, body').animate({
scrollTop: $(elements[index]).offset().top
}, 1000);
if(index < (elements.length - 1)){
index++;
} else {
index = 0;
}
}
});
});
</script>

See this JSFiddle: https://jsfiddle.net/3gb5uLgs/
I added this function
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
2: You can use location.reload();.

You need to add ScrollTop function, and use it when you reach bottom.
$(document).ready(function () {
var myInterval = false;
myInterval = setInterval(AutoScroll, 5000);
function AutoScroll() {
var iScroll = $(window).scrollTop();
iScroll = iScroll + 500;
$('html, body').animate({
scrollTop: iScroll
}, 1000);
}
//The function scroll to 0 position.
function scrollTop()
{
$('html, body').animate({
scrollTop: 0
}, 1000);
}
$(window).scroll(function () {
var iScroll = $(window).scrollTop();
if (iScroll == 0) {
clearInterval(myInterval);
myInterval = setInterval(AutoScroll, 5000);
}
if (iScroll + $(window).height() == $(document).height()) {
clearInterval(myInterval);
//Instead refresh, I just scrolled to top.
setTimeout(scrollTop,5000)
}
});
});

Related

On scroll the active menu does not chaning

I've created a right side menu but when i scrolling down it is not changing the active class to next menu,I've used this code lots of time but this time i'm not getting the result,
$(window).scroll(function() {
var scrollbarLocation = $(this).scrollTop();
scrollLink.each(function() {
var sectionOffset = $(this.hash).offset().top - 70;
if ( sectionOffset <= scrollbarLocation ) {
$('.icons').removeClass('iconactive');
$(this).children('.icons').addClass('iconactive');
}
});
});
DEMO
you need to define scrollLink and you can give some animation effect when you click an anchor link by adding a function like this
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1000);
});
Demo : http://jsfiddle.net/3xmop98u/
I think you are missing var scrollLink = $('.myanimate'); in your code. Adding this line in your DEMO make the code work.
$(window).scroll(function() {
var scrollbarLocation = $(this).scrollTop();
var scrollLink = $('.myanimate');
scrollLink.each(function() {
var sectionOffset = $(this.hash).offset().top - 70;
if ( sectionOffset <= scrollbarLocation ) {
$('.icons').removeClass('iconactive');
$(this).children('.icons').addClass('iconactive');
}
});
});
$(".myanimate").click(function (){
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top
}, 2000);
});

How to make slow the Scroll-Top Speed

ScrollTop is a jquery plugin (go to top of page), trying to make slow Scroll Speed, but not working. I have changed scrollSpeed : 'fast', to scrollSpeed : 'slow', but it still fast, nothing change.
JS:
$.fn.extend({
addScrollTop: function(options) {
var defaults = {
useObjWindow : false,
scrollSpeed : 'fast',
zIndex: '99'
}
var options = $.extend(defaults, options);
if($('body').find('.scrollTop-btn').length == 0) {
$('body').append('<div class="scrollTop-btn" style="display:none;"><i class="fa fa-chevron-up"></i></div>');
}
if(options.useObjWindow) {
var parentWindow = this;
var scrollWindow = this;
}
else {
var parentWindow = window;
var scrollWindow = 'html, body';
}
$(document).ready(function() {
$('.scrollTop-btn').on('click', function() {
$(scrollWindow).animate({scrollTop:0}, options.scrollSpeed);
});
$(parentWindow).scroll(function() {
$('.scrollTop-btn').hide();
var aTop = $('.scrollTop-btn').height() + 20;
if($(this).scrollTop() >= (aTop + 20)) {
$('.scrollTop-btn').css('z-index', options.zIndex);
$('.scrollTop-btn').show();
}
else {
if($('.scrollTop-btn').is(":visible")) {
$('.scrollTop-btn').hide();
}
}
});
});
}
});
Call:
jQuery(document).ready(function() {
jQuery("body").addScrollTop();
});
How to make it slower or smoother, when it go to top?
use jquery animate()
$('html,body').animate({ scrollTop: 0 }, 'slow');
refer this stack overflow question
Only with CSS:
html {
scroll-behavior: smooth;
}
Using jQuery
If you want you can customize how much time you would like the "scrolling" to last. Or do something else when scroll effect is finished.
I have a: <a href="#" class="scrollToTop">
And want to scroll to an element with class "beginning"
$('.scrollToTop').on('click', function(event){
event.preventDefault();
$('html, body').stop().animate({scrollTop: $('.beginning').offset().top}, 500);
});
The last part where you have the 500. You can set there how much time you want the effect to last. In milliseconds.
http://api.jquery.com/animate/
Replace 'slow' with - Ex. 1000, 5000, 10000
$('html,body').animate({ scrollTop: 0 }, <milliseconds>);
// Scroll 2 sec
$('html,body').animate({ scrollTop: 0 }, 2000);
// Scroll 5 sec
$('html,body').animate({ scrollTop: 0 }, 5000);

Scroll to Top jQuery

I am trying to create a super simple Scroll to top button.
It works but it's appending the button to the body every time when i scroll.
I would like to append it only once and fade it in and if you click it you will be scrolled back to the top off the page and it will fadeout.
The functionality is working but its appending it to the page in an loop.
I know it's a simple bug but, I can't figure it out.
My code:
$(window).scroll(function () {
var scrollPosition = $(this).scrollTop();
var to_top = '<a class="back-to-top" href="#"></a>';
if (scrollPosition >= 500) {
$("body").append(to_top);
$('.back-to-top').fadeIn(1600);
} else {
$('.back-to-top').fadeOut(800);
}
$( ".back-to-top" ).on( "click", function(event) {
event.preventDefault();
$("html, body").animate({ scrollTop: 0 }, "slow");
});
});
Well, you're telling it to append the every time the scroll event is fired, so check if it exists first, see if it works out for you.
$(window).scroll(function () {
var scrollPosition = $(this).scrollTop();
var toTops = $('.back-to-top'); // get jQ object once
if (scrollPosition >= 500) {
if (!toTops.length){ // if no elems
// create one
var $to_top = $('<a class="back-to-top" href="#"></a>');
$to_top.on( "click", function(event) {
event.preventDefault();
$("html, body").animate({ scrollTop: 0 }, "slow");
});
// then attach it
$("body").append($to_top);
} else {
// if elems exist, fade them in
toTops.fadeIn(1600);
}
} else {
toTops.fadeOut(800);
}
});
You should create button once and then hide/show it.
jQuery(function($) {
var to_top = $('<a class="back-to-top" href="#"></a>'),
visible = false;
to_top.appendTo('body').hide();
$( ".back-to-top" ).on( "click", function(event) {
event.preventDefault();
$("html, body").animate({ scrollTop: 0 }, "slow");
});
$(window).scroll(function () {
if ($(this).scrollTop() >= 500)
if(!visible){
to_top.stop(true,false).fadeIn(1600);
visible = true;
}
else
if(visible){
to_top.stop(true,false).fadeOut(800);
visible = false;
}
});
});

Javascript scroll to element on scroll

I searched very long but haven't found a soulution yet.
I want to scroll to the next element on scroll.
$(window).load(function(){
var scroll = false;
$(function() {
//Create an Array
var sites = $('.site');
var position = 0; //Start Position
var next = $('#next');
var lastScrollTop = 0;
$(window).scroll(function(event){
if(scroll == false){
scroll = true;
$(document).off('scroll');
var st = $(this).scrollTop();
if (st > lastScrollTop){
if (position !== sites.length - 1) {
scrollToPosition(sites[position += 1]),5000;
}
} else {
if (position !== 0) {
scrollToPosition(sites[position -= 1]),5000;
}
}
lastScrollTop = st;
}
});
})
function scrollToPosition(element) {
if (element !== undefined) {
scrollToElement($(element).attr('id'));
}
}
function scrollToElement(selector, time, verticalOffset) {
time = typeof(time) != 'undefined' ? time : 500;
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
selector = "#" + selector;
var element = $(selector);
offset = element.offset();
offsetTop = offset.top + verticalOffset;
$('html, body').animate({
scrollTop: offsetTop
}, time);
scroll = false;
}
});
the html has many of these with different ids
<div id="test" style="width:100%; height:100vh;" class="site">
</div>
So the containers are fullscreen hight. and when the user scrolls a bit he should get to the next container.
At the moment it scrolls till the end and or more.
It would help if you could create an example in jsFiddle or CodePen, but the first thing I would do is stop any current jQuery animations before launching new ones:
$('html, body').stop().animate({
scrollTop: offsetTop
}, time);
You should keep in mind that scroll handler is executed many times when user is scrolling.
Also, unrelated - your scrollToPosition calls have brackets at the wrong place and should probably be like this:
scrollToPosition(sites[position += 1], 5000);
Edit:
Another thing that might cause problems - you should unset the 'scroll' flag/variable only when the animation has finished, something like this:
$('html, body').stop().animate({
scrollTop: offsetTop
}, time, function () {
scroll = false;
});

How to scroll once in $(window).scroll() have another scroll command

I have a vertical photo viewer
and i need a scroll effect is once a page height when mouse wheel down.
so i have following code
$(document).ready(function() {
$(window).scroll(function () {
var H = $(window).height();
var st = $(this).scrollTop();
$("html, body").animate({ scrollTop: H + st }, 500, function () {
console.log("finish scroll");
});
});
});
But when i scroll once, it will repeat again and again until to the bottom.
How can i solve this problem?
Thanks in advance.
I used a counter and a timer so that the counter waits half a second after the scroll has finished..
http://jsfiddle.net/beardedSi/p45rH/1/
$(document).ready(function () {
var H = $(window).height(),
go = true;
console.log(H);
//just for visual, set the height of boxes to be same as window height
//to check it is all working
$('.box').css('height', H + "px");
function scroller() {
$("html, body").animate({
scrollTop: '+=' + H
}, 400, function () {
console.log("finished");
setTimeout(function () {
go = true;
}, 400);
});
}
$(document).on('scroll', function (e) {
e.preventDefault();
if (go) {
go = false;
scroller();
}
});
});
The problem is the animation make a scroll event too. so you have a scrolling loop.
To resolve that, you can add a flag.
It's not the best way to solve your problem but you can do this => http://jsbin.com/qagayopu/2/edit

Categories