Animate element on user scroll - javascript

I am currently using the logic below to animate a navigation block. It is working well when user scroll greater than 5px, the element animates out of the viewport. However the user must scroll top top of window for the element to animate back into position.
Rather than waiting for the user to scroll to the top of page how do I trigger the animate function as soon as a user scrolls up? (Not waiting till they get to the top of page)
var _throttleTimer = null;
var _throttleDelay = 100;
var $window = $(window);
var $document = $(document);
$document.ready(function () {
$window
.off('scroll', ScrollHandler)
.on('scroll', ScrollHandler);
});
function ScrollHandler(e) {
clearTimeout(_throttleTimer);
_throttleTimer = setTimeout(function () {
//console.log('scroll');
if($(window).scrollTop() > 5) {
$( ".mobile_header .content" ).animate({
top: "-34px"
}, 100 );
} else {
////Need help here
$( ".mobile_header .content" ).animate({
top: "34px"
}, 100 );
}
}, _throttleDelay);
}

Heres is the solution. had to modify logic to detect if the user scroll down or scroll up.
var _throttleTimer = null;
var _throttleDelay = 100;
var lastScrollTop = 0;
var $window = $(window);
var $document = $(document);
$document.ready(function () {
$window
.off('scroll', ScrollHandler)
.on('scroll', ScrollHandler);
});
function ScrollHandler(e) {
clearTimeout(_throttleTimer);
_throttleTimer = setTimeout(function () {
console.log('scroll');
var st = $(this).scrollTop();
if (st > lastScrollTop && $(window).scrollTop() > 5){
$( ".mobile_header .content" ).animate({
top: "-34px"
}, 100 );
} else {
$( ".mobile_header .content" ).animate({
top: "34px"
}, 100 );
}
lastScrollTop = st;
}, _throttleDelay);
}

Related

When the window is loading the event stops. After scrolling down the event starts

(function () {
var previousScroll = 0;
$(window).scroll(function(){
var currentScroll = $(this).scrollTop();
if (currentScroll > previousScroll){
event.preventDefault();
}
previousScroll = currentScroll;
});
}());
$(window).on('load', function () {
$(".timer").timerstart({
event.stopPropagation()l
});
});
is it possible?
when the page is begin event is stopping and scroll down event start.

jQuery jQuery-min conflict

and let me tell you in advance that the no-conflict script didnt work either, my issue is this:
I have a site that i made, i made some animations for it, using the animate library and some other animations
$(document).ready(function ($) {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 1000, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('.nav-ul-home a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('.navbar-home ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 100) {
$(".navbar-home").addClass("navbar-section");
$(".nav-ul-home").addClass("nav-ul-section");
}
else{
$(".navbar-home").removeClass("navbar-section");
$(".nav-ul-home").removeClass("nav-ul-section");
}
});
$(function() {
var Accordion = function(el, multiple) {
this.el = el || {};
// more then one submenu open?
this.multiple = multiple || false;
var dropdownlink = this.el.find('.dropdownlink');
dropdownlink.on('click',
{ el: this.el, multiple: this.multiple },
this.dropdown);
};
Accordion.prototype.dropdown = function(e) {
var $el = e.data.el,
$this = $(this),
//this is the ul.submenuItems
$next = $this.next();
$next.slideToggle();
$this.parent().toggleClass('open');
if(!e.data.multiple) {
//show only one menu at the same time
$el.find('.submenuItems').not($next).slideUp().parent().removeClass('open');
}
}
var accordion = new Accordion($('.accordion-menu'), false);
})
and this is my animations script
$(window).on('scroll', function (e) {
var top = $(window).scrollTop() + $(window).height(),
isVisible = top > $('#texto p').offset().top;
$('#texto p').toggleClass('animated fadeInUp', isVisible);
});
$(window).on('scroll', function ($) {
var top = $(window).scrollTop() + $(window).height(),
isVisible = top > $('in img').offset().top;
$('in img').toggleClass('magictime tinRightIn', isVisible);
});
$(window).on('scroll', function ($) {
var top = $(window).scrollTop() + $(window).height(),
isVisible = top > $('in p').offset().top;
$('in p').toggleClass('magictime puffIn', isVisible);
});
I only put some of it cause it basically repeats its self for every case....
now... I have links to both jquery and jquery-min i need the jquery for this code and the jquery-min for the contact form, the problem is that when i have both links the animations dont work...
if i remove the jquery-min link everything is fine but the contact form doesnt work...
maybe if someone has a contact form template that has JS but doesnt need jquery-min the problem is solve..
sorry for my aqward way to post im prety new here.
thanks!

jQuery scrollTop() returns wrong offset on scroll-direction change

I'm trying to get the correct scroll direction via jQuery's "scroll" event.
For this, I'm using the solution here: https://stackoverflow.com/a/4326907/8407840
However, if I change the direction of my scroll, the offset returned by scrollTop is incorrect on the first time. This results in the following behavior:
Wheel down -> down
Wheel down -> down
Wheel up -> down
Wheel up -> up
Wheel down -> up
Wheel down -> down
... and so on, I think you get it.
var ACTIVE_SECTION = null;
var ANIMATION_DURATION = 700;
$(document).ready(function() {
ACTIVE_SECTION = $("section:first-of-type").get(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", function() {
doScrollingStuff(prevPosition);
});
});
function doScrollingStuff(prevPosition) {
var ctPosition = $(window).scrollTop();
var nextSection = ACTIVE_SECTION;
// Remove and re-append event, to prevent it from firing too often.
$(window).off("scroll");
setTimeout(function() {
$(window).on("scroll", function() {
doScrollingStuff(prevPosition);
});
}, ANIMATION_DURATION + 100);
// Determine scroll direction and target the next section
if(ctPosition < prevPosition) {
console.log("up");
nextSection = $(ACTIVE_SECTION).prev("section").get(0);
} else if(ctPosition > prevPosition) {
console.log("down");
nextSection = $(ACTIVE_SECTION).next("section").get(0);
}
// If a next section exists: Scroll to it!
if(typeof nextSection != 'undefined') {
var offset = $(nextSection).offset();
$("body, html").animate({
scrollTop: offset.top
}, ANIMATION_DURATION);
ACTIVE_SECTION = nextSection;
} else {
nextSection = ACTIVE_SECTION;
}
console.log(ACTIVE_SECTION);
prevPosition = ctPosition;
}
section {
width:100%;
height:100vh;
padding:60px;
box-sizing:border-box;
}
section:nth-child(1) { background:#13F399; }
section:nth-child(2) { background:#14FD43; }
section:nth-child(3) { background:#4EE61E; }
section:nth-child(4) { background:#BEFD14; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="sect1">Section 1</section>
<section id="sect2">Section 2</section>
<section id="sect3">Section 3</section>
<section id="sect4">Section 4</section>
Here's a pen, where you can see my implementation: https://codepen.io/EigenDerArtige/pen/aVEyxd
I am trying to accomplish an autoscroll to the next or previous section, whenever the user scrolls or swipes up/down... Therefore I only fire the "scroll"-event once every second, to prevent multiple scrolljacks all happening at once... However the above behavior seems to result in the user being scrolled to the wrong section.
I've been trying for a couple of hours now to get it working, but to no avail. Help is greatly appreciated!
The problem lies in the assignment prevPosition = ctPosition.
Each time the scroll handler runs, var ctPosition = $(window).scrollTop(); is good for determining scroll direction, however it's not the value that should be rememberad as prevPosition.
prevPosition needs to be $(window).scrollTop() as measured after the animation has completed.
Try this :
$(document).ready(function() {
var ANIMATION_DURATION = 700;
var ACTIVE_SECTION = $("section:first-of-type").eq(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", doScrollingStuff);
function doScrollingStuff(e) {
$(window).off("scroll");
var ctPosition = $(window).scrollTop();
var nextSection = (ctPosition < prevPosition) ? ACTIVE_SECTION.prev("section") : (ctPosition > prevPosition) ? ACTIVE_SECTION.next("section") : ACTIVE_SECTION; // Determine scroll direction and target the next section
// If next section exists and is not current section: Scroll to it!
if(nextSection.length > 0 && nextSection !== ACTIVE_SECTION) {
$("body, html").animate({
'scrollTop': nextSection.offset().top
}, ANIMATION_DURATION).promise().then(function() {
// when animation is complete
prevPosition = $(window).scrollTop(); // remember remeasured .scrollTop()
ACTIVE_SECTION = nextSection; // remember active section
$(window).on("scroll", doScrollingStuff); // no need for additional delay after animation
});
} else {
setTimeout(function() {
$(window).on("scroll", doScrollingStuff);
}, 100); // Debounce
}
}
});

Scrolling sidebar inside a div with scrollbar - $(window).on('scroll', function()?

I want my social sidebar make scroll only within the gray div. I have already put the sidebar within the gray div does not exceed the footer or the content above. My difficulty is to sidebar scroll accompanying the scroll without going gray div.
http://test.eae.pt/beautyacademy/angebot/
JS:
beautyAcademy.sharer = {
element: void 0,
elementToScroll: void 0,
init:function() {
this.element = $('.js-sharer-ref');
console.log(this.element.length);
if(this.element.length != 1) {
return;
}
this.build();
},
build: function() {
this.binds();
},
binds: function() {
var _this = this;
// Element that's gonna scroll
this.$elementToScroll = $('.fixed-social');
// Element that's gonna scroll height
this.elementToScrollHeight = this.$elementToScroll.outerHeight();
// Element where scroll is gonna happen Height
this.elementHeight = this.element.outerHeight();
// Element where scroll is gonna happen distance to top
this.elementOffsetTop = this.element.offset().top;
// Scroll that was done on the page
this.windowScrollTop = $(window).scrollTop();
this.elementOffsetBottom = this.elementOffsetTop + this.elementHeight - this.elementToScrollHeight;
this.$elementToScroll.css('top', (_this.elementOffsetTop+80) + "px");
$(window).on('scroll', function() {
if(this.windowScrollTop + this.elementToScrollHeight < this.elementHeight )
this.$elementToScroll.css('margin-top', this.windowScrollTop );
});
}
};
You need to try like below :
$(function(){
if ($('#container').length) {
var el = $('#container');
var stickyTop = $('#container').offset().top; // returns number
var stickyHeight = $('#container').height();
$(window).scroll(function(){ // scroll event
var limit = $('#footer').offset().top - stickyHeight - 20;
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});
DEMO

Reposition DIV after scrolling

I have a navigation bar that repositions after scrolling down. It works with position:fixed, but while scrolling I want it to move up like all the other content that follow on the site . I the user stops scrolling it should reposition on top:
Heres a demo:
http://jsfiddle.net/gvjeyywa/7/
But I want it to be position:absolute (especially for the scrolling on the Ipad)
http://jsfiddle.net/gvjeyywa/5/
How do i let the JS overide my CSS? Here is my JS:
var isInAction = false;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
if (!isInAction){
isInAction = true;
$( "#navigation" ).animate({
top: "-" + $("#navigation").innerHeight() + "px"
}).delay(1000).animate({
top: "0px"
}, 800, function() {
isInAction = false;
});
}
}
lastScrollTop = st;
});
In the first look i think it's impossible but after some tries this code was created.
I spent long time to write this code and use several techniques and hope to be helpful.
Maybe there are simpler solutions too !!
var bitFlag = false;
var lastScrollTop = 0;
var timeoutId;
$navigation = $("#navigation");
$(window).scroll(function (event) {
var intWindowTop = $(window).scrollTop();
var intElementBottom = $navigation.offset().top + $navigation.innerHeight();
if (intWindowTop > lastScrollTop) {
if (!bitFlag) {
$navigation.css("position", "absolute").css("top", intWindowTop + "px");
bitFlag = true;
}
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function () {
if (intWindowTop > intElementBottom) {
intDelayTime = setTimeout(function () {
$navigation.animate({
top: intWindowTop + "px"
}, 800);
}, 500);
}
}, 100);
} else {
$navigation.css("position", "fixed").css("top", "0px");
bitFlag = false;
}
lastScrollTop = intWindowTop;
});
The }, 500); section control Delay time in milliseconds and the }, 800); section control the slide down animation speed.
Check JSFiddle Demo

Categories

Resources