jQuery Scroll up/down animations blocking - javascript

I have a problem regarding two animations, one scrolling down and one scrolling up (when the user has scrolled back up completely).
The animations block each other - with the following source code:
jQuery(document).ready(function($) {
$(window).on("load",function() {
$(window).scroll(function(){
if($(window).offset().top == 0){
$("selector").animate({}, 500);
$("selector").animate({}, 500);
} else {
$("selector").animate({}, 500);
$("selector").animate({}, 500);
}
});
}).scroll();
});
So it happens that after the true statement block of the if directly the else part is executed again and therefore the animation is partly not executed at all or both are executed one after the other. Does anyone have an idea that the animations are executed reliably:
else animation once as soon as scrolling down was done
if-Animation as soon as scrolling up completely again
Thanks in advance!

Makes no sense to cauculate $(window).offset().top since... it does what it says. 0.
Perhaps, on "scroll" Event you want to get the $(window).scrollTop()
jQuery($ => {
const $win = $(window);
const $items = $(".item");
$win.on("scroll", () => {
$items.toggleClass("active", $win.scrollTop() == 0);
});
$win.on("load", () => {
$win.trigger("scroll");
});
});
.active {
/* your styles here */
}

Related

jQuery toggleClass doesn't fire work resizing browser?

I have an issue with some code. Basically on click of a div the class 'active-sort' should be added/removed (This class changes the position of .sort-by from the top). On page load it works great but for some reason the toggleClass doesn't always work when the browser is resized (sometimes it does, sometimes it doesn't).
I'm not great with this, so was hoping a new set of eyes might be able to instantly see what I'm doing wrong. Any help would be appreciated.
function toggleSortBy() {
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by');
if ($(window).width() > 1024) {
toggle.click(function(){
sortBy.toggleClass('active-sort');
});
} else {
// other code here for smaller devices
}
};
$(window).on('load resize', function() {
toggleSortBy();
});
it's possible you may not need the resize event since you're checking the window size already in the click handler
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by');
toggle.click(function(){
if ($(window).width() > 1024) {
sortBy.toggleClass('active-sort');
} else {
// other code here for smaller devices
}
});
but if you do you should debounce the resize event
//css-tricks.com/snippets/jquery/done-resizing-event
then you could do something like:
var toggle = $('.sort-banner-row'),
sortBy = $('.sort-by'),
isMobile = false;
toggle.click(function(){
if (isMobile) {
sortBy.toggleClass('active-sort');
} else {
// other code here for smaller devices
}
});
$(window).on('load resize', function() {
// don't forget to debounce you'll see why later on in your development.
isMobile = ($(window).width() > 1024) ? false : true;
});

Javascript odd behaviour on mouse scroll up / down classes

I'm hoping a Javascript wiz can help a fellow citizen out with resolving a problem. I've a fairly straight forward function. When I scroll down by 1px I would like to apply a bounceDown class, this will run for 5 seconds and the class will then disappear for future running of the same function.
When I scroll up from that current scroll position I would like the bounceUp effect to apply. However the issue is I think the bounceUp effect only works once you scroll past the original scroll but in addition to this if the previous function is still running on it's 5 second transition then it gets jumpy as it's trying to run two classes at the same time so there almost needs to be a delay applied.
Does anyone think they can help, I'd gratefully appreciate it.
<script>
(function($){
$.fn.extend({
addTemporaryClass: function(className, duration) {
var elements = this;
setTimeout(function() {
elements.removeClass(className);
}, duration);
return this.each(function() {
$(this).addClass(className);
});
}
});
})(jQuery);
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 1) {
$(".spanner").addTemporaryClass("BounceDown", 5000);
}
else if (scroll <= 1) {
$(".spanner").addTemporaryClass("BounceUp", 5000);
}
});
</script>
What about a boolean variable that is 'true' when addTemporaryClass is running? So:
(function($){
var classAdded = false; //New
$.fn.extend({
addTemporaryClass: function(className, duration) {
classAdded = true; //New
var elements = this;
setTimeout(function() {
elements.removeClass(className);
classAdded = false; //New
}, duration);
return this.each(function() {
$(this).addClass(className);
});
}
});
})(jQuery);
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 1 /*New*/ && !classAdded /*New*/) {
$(".spanner").addTemporaryClass("BounceDown", 5000);
}
else if (scroll <= 1 /*New*/ && !classAdded /*New*/) {
$(".spanner").addTemporaryClass("BounceUp", 5000);
}
});

Scrolling jQuery

I have some code that is supposed to scroll one page height every time scroll is triggered in some way. I want this to scroll only one heigh, and "pause" the trigger until the scrolling is done. However, my script does not stop, instead it will scroll all the way down instantly. Scrolling upwards seems to work better...
Here is my script:
var lastScroll = 0;
var scrollPos = 0;
var blockScroll = 0;
$(window).scroll(function() {
var scroll = $(this).scrollTop();
if(blockScroll == 0) {
blockScroll = 1;
if(scroll > lastScroll){
// Down
scrollPos++;
console.log(scrollPos+"-"+blockScroll);
$("html, body").animate({scrollTop:$(window).height()*scrollPos}, 'slow', function() {
blockScroll = 0;
});
} else {
// Up
scrollPos--;
console.log(scrollPos);
$("html, body").animate({scrollTop:$(window).height()*scrollPos}, 'slow', function() {
blockScroll = 0;
});
}
}
lastScroll = scroll;
});
blockScroll is meant to be set when a scroll event appears, and to be unset when the scrolling animation stops. As a lock. I am not shure this works the way I want it though... Can someone see something obviously wrong with this? Am I having trouble with the fact that jQuery is async?
It appears that animate is firing scroll events itself, so when it finishes, it's firing one last scroll event which restarts the process.
It seems like adding a small timeout in the callback solves the problem:
setTimeout(function () {blockScroll = 0;}, 50)
http://jsfiddle.net/qch787yq/1/

prevent animation double click issue

Hi I have problem with my slider please visit this site and check http://paruyr.bl.ee/
after click on my arrows it becomes work in an asynchronous way, ones it changes very fast and then slow and it repeats.
I think it is from start slider and stop slider.
var sliderPrev = 0,
sliderNext = 1;
$("#slider > img").fadeIn(1000);
startSlider();
function startSlider(){
count = $("#slider > img").size();
loop = setInterval(function(){
if (sliderNext>(count-1)) {
sliderNext = 0;
sliderPrev = 0;
};
$("#slider").animate({left:+(-sliderNext)*100+'%'},900);
sliderPrev = sliderNext;
sliderNext=sliderNext+1;
},6000)
}
function prev () {
var newSlide=sliderPrev-1;
showSlide(newSlide);
}
function next () {
var newSlide=sliderPrev+1;
showSlide(sliderNext);
}
function stopLoop () {
window.clearInterval(loop);
}
function showSlide(id) {
stopLoop();
if (id>(count-1)) {
id = 0;
} else if(id<0){
id=count-1;
}
$("#slider").animate({left:+(-id)*100+'%'},900);
sliderPrev = id;
sliderNext=id+1;
startSlider();
};
$("#slider, .arrows").hover(function() {
stopLoop()
}, function() {
startSlider()
});
function onlyNext () {
var newSlide=sliderPrev+1;
onlyShowSlide(newSlide);
}
function onlyShowSlide(id) {
if (id>(count-1)) {
id = 0;
} else if(id<0){
id=count-1;
}
$("#slider").animate({left:+(-id)*100+'%'},900);
sliderPrev = id;
sliderNext=id+1;
};
I think the best option would be to check if the animation is in progress and prevent the action if it is, something like this:
function prev () {
if(!$('#slider').is(":animated"))
{
var newSlide=sliderPrev-1;
showSlide(newSlide);
}
}
function next () {
if(!$('#slider').is(":animated"))
{
var newSlide=sliderPrev+1;
showSlide(sliderNext);
}
}
To illustrate the difference between this and just sticking a stop() in, check this JSFiddle. You will notice some choppy movements if you click multiple times in the stop() version.
What I would do is add a class to your slider when the animation starts and remove the class when it finishes:
$("#slider").animate({left:+(-id)*100+'%'}, {
duration: 900,
start: function() {
$('#slider').addClass('blocked');
},
complete: function() {
$('#slider').removeClass('blocked');
}
});
Now check on each click event if the slider is blocked or not:
function next () {
if (!$('#slider').hasClass('blocked')) {
var newSlide=sliderPrev+1;
showSlide(sliderNext);
}
}
This is a very simple solution, I'm sure there is a better one.
EDIT: As marcjae pointed out, you could stop the animations from queuing. This means when you double click, the slideshow still will move 2 slides. With my approach the second click will be ignored completely.
You can use a variable flag to control if the animation is still being done, or simply use .stop() to avoid stacking the animation.
$("#pull").click(function(){
$("#togle-menu").stop().slideToggle("slow");
});
It is occurring because your animations are being queued.
Try adding:
.stop( true, true )
Before each of your animation methods. i.e.
$("#slider").stop( true, true ).animate({left:+(-id)*100+'%'},900);
The answers about stop are good, but you have a bigger issue that is causing the described behavior. The issue is here:
$("#slider, .arrows").hover(function() {
stopLoop()
}, function() {
startSlider()
});
You have bound this to the .arrows as well as the #slider and the arrows are contained within the slider. So, when you mouse out of an arrow and then out of the entire slider, you are calling start twice in a row without calling stop between. You can see this if you hover onto the arrow and then off of the slider multiple times in a row. The slides will change many times after 6 seconds.
Similarly, consider the case of a single click:
Enter the `#slider` [stopLoop]
Enter the `.arrows` [stopLoop]
Click the arrow [stopLoop]
[startSlider]
Leave the `.arrows` [startSlider]
Leave the `#slider` [startSlider]
As you can see from this sequence of events, startSlider is called 3 times in a row without calling stopLoop inbetween. The result is 3 intervals created, 2 of which will not be stopped the next time stopLoop is called.
You should just have this hover on the #slider and more importantly, add a call to stopLoop as the first step in startSlider. That will ensure that the interval is always cleared before creating a new one.
$("#slider").hover(function() {
stopLoop()
}, function() {
startSlider()
});
function startSlider(){
stopLoop();
/* start the slider */
}

Slow/unresponsive animation with jQuery animation

I am writing a small jQuery function and I seem to be having trouble.
What I am trying to do here is when the user scrolls down the page by 90px, a div tag should animate down (from top:-50px to top:0), and vice-versa when they scroll back to the top of the page.
The problem I am having is that the animation seems to be very slow and unresponsive at times. I test in 3 different browsers and different computers but I am having no joy.
Here is my code:
// Show div
var scrollValue = "90";
// Animate functions
var showHead = function (){
$(".element").animate({top: "0"}, 250);
}
var hideHead = function (){
$(".element").animate({top: "-50px"}, 250);
}
$(window).scroll(function() {
if ($(this).scrollTop() > scrollValue) {
showHead();
} else {
hideHead();
}
});
The .element properties:
.element { positoin:fixed; top:-50px; }
Could anyone figure out why my code the hide/showHead functions are so sloppy?
Thanks,
Peter
The scroll event is triggered several times and even though it is rate-limited it keeps being a rather intensive operation. Actually, you may be queuing several animations and the fx stack may be growing very quickly.
One possibility you can try is stopping all previous animations before triggering a new one. You can do this by using .stop().
$(".element").stop().animate({top: "0"}, 250);
The .stop() function also provides some other options which you can use to tweak it even more.
Try this one :
$(window).scroll(function() {
if (window.scrollY > scrollValue) {
showHead();
} else {
hideHead();
}
});
scroll events occurred many time durring user scrolling.
You need to check if your animation is in progress before starting the animation again.
Try this :
// Show div
var scrollValue = "90";
var inProgress = false;
// Animate functions
var showHead = function () {
if(inProgress)
return false;
//Animate only if the animation is not in progress
inProgress = true;
$(".element").animate({
top: "0"
},250,function(){
inProgress = false; //Reset when animation is done
});
}
var hideHead = function () {
if(inProgress)
return false;
//Animate only if the animation is not in progress
inProgress = true;
$(".element").animate({
top: "-50px"
}, 250,function(){
inProgress = false; //Reset when animation is done
});
}
$(window).scroll(function () {
if ($(this).scrollTop() > scrollValue) {
showHead();
} else {
hideHead();
}
});
Assuming you have position:fixed (or some other sort of styling making the bar visible when necessary):
var scrollheight = 90;
var $el = $('.element');
function showHead(){
$el.stop().animate({
top: '0px'
}, 250);
}
function hideHead(){
$el.stop().animate({
top: '-50px'
}, 250);
}
$(window).scroll(function(){
if ($(window).scrollTop() > scrollheight){
showHead();
}else{
hideHead();
}
});
example: http://jsfiddle.net/L4LfL/
try using queue: false and as Alexander said use .stop()
here jsfiddle
http://jsfiddle.net/hwbPz/

Categories