Animation issues using setInterval - javascript

I'm animating a div to left by 0px by clicking on the div colored in red. Below the div , classes are added to li's as the div moves along, but the classes gets added to only certain li's and not all.
Is there any other logic to fix this ?
Fiddle - http://jsfiddle.net/AsfFQ/16/
Below is the image of the issue

Try this jsFiddle example.
var pos;
var timer, selectLi = (function() {
var $block = $('.block'),
$container = $('.container'),
$lis = $('.container ul li'),
liWidth = $lis.width(),
$selectedLi;
return function() {
pos = $block.offset().left - $container.offset().left;
liNum = Math.round(pos / liWidth);
// $selectedLi && $selectedLi.removeClass('selected');
$selectedLi = $($lis.get(liNum));
$('li.eligible').each(function() {
if ($block.offset().left-3 <= $(this).offset().left) $(this).addClass('selected');
});
};
})();
$('.block').click(function() {
timer = setInterval(selectLi, 30);
$(this).animate({
left: 0
}, function() {
clearInterval(timer);
});
});
$('li').each(function() {
$(this).addClass('eligible');
if ($(this).offset().left > $('.block').offset().left) $(this).removeClass('eligible');
});​
This sets the eligible list items and then as the bar moves, compares their position to tjat of the bar and if they're in range, they get the class added.

Your little animation needs only a little code.
See jsfiddle example
var $block = $('.block'),
start = $block.offset().left;
$block.one('click').animate({left: 0})
.$('li').filter(function(){return $(this).offset().left<=start})
.repeat(30).filter(function(){return $(this).offset().left>=$block.offset().left})
.addClass('selected').unrepeat();
​
I'm using this plugin jquery-timing.
This also works when animating 100px on each click, see another fiddle:
var $block = $('.block');
$block.on('click').animate({left: '-=100px'})
.$('li').filter(function(){return $(this).offset().left<=$block.offset().left})
.repeat(30).filter(function(){return $(this).offset().left>=$block.offset().left})
.addClass('selected').unrepeat();
Have fun!

Related

using css class in js to redirect after certain number of clicks

I'm trying to expand on previous js code you all helped me out with in the past. The code creates a slideshow of cars and their pricing on a webpage, pulling the data from a mysql db. I had it working where it would redirect to a new page after a minute of time, but now I want the redirect to happen when the total number of plays equals the number of slides * 2. I am not experienced with js and any help would be great...
Here is the code that creates slideshow... (jscript.js)
$(document).ready(function(){
var currentPosition = 0;
var slideWidth = 1280;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div>')
// Float left to display horizontally, readjust .slides width
.css({
'float' : 'left',
'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert controls in the DOM
$('#slideshow')
.prepend('<span class="control" id="leftControl"></span>')
.append('<span class="control" id="rightControl"></span>');
// Hide left arrow control on first load
manageControls(currentPosition);
// Create event listeners for .controls clicks
$('.control')
.bind('click', function(){
// Determine new position
currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
// Hide / show controls
manageControls(currentPosition);
// Move slideInner using margin-left
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
}, function() {
// if last slide then move the pointer to 1st slide
if(currentPosition == numberOfSlides-1) {
currentPosition = -1;
}
});
});
window.setInterval(function() {
$('#rightControl.control').click();
}, 3000);
// manageControls: Hides and Shows controls depending on currentPosition
function manageControls(position){
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{$('#rightControl').show() }
}
});
Im thinking the code to redirect would be something like... (nextpage.js)
$(document).ready(function(){
var currentPosition = 0;
var slides = $('.slide');
var numberOfSlides = slides.length;
var clicks = $('.control');
var slidesPlayed = clicks.length;
if(numberOfSlides == (slidesPlayed * 2)){
window.location.href = "https://www.cars.com";
}
});
Any help would be greatly appreciated.
Thank you!
Freshly tested:
$(document).ready(function(){
var slidesPlayed = 0;
var whatever = 5; //that would be the total slides * 2 if I understand what you want, but let's say it's 5 for this example
$('#thetrigger').on("click", function() {
slidesPlayed++;
console.log(slidesPlayed);
if(slidesPlayed >= whatever){
window.location.href = "https://www.cars.com";
}
});
});
If you click #trigger whatever times, you get redirected.

Jquery - How to loop this slider?

So I've been working on a slider and I don't really know how to make it repeat itself. So far I've only listed 10 slides but in the end I'll have around 20.
Here's a link to a JS fiddle so you can see what I've got so far:
https://jsfiddle.net/sth23e2w/
$(document).ready(function() {
//settings for slider
var width = 360;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;
//cache DOM elements
var $slider = $(".characters");
var $slideContainer = $(".slide-characters", $slider);
var $slides = $(".char-avatar", $slider);
$(".right-slide").click(function() {
$slideContainer.animate(
{ "margin-left": "+=" + width },
animationSpeed,
function() {
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css("margin-left", 0);
}
}
);
});
$(".left-slide").click(function() {
$slideContainer.animate(
{ "margin-left": "-=" + width },
animationSpeed,
function() {
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css("margin-left", 0);
}
}
);
});
});
Or if you really want you could check out the live version I've got over at Codepen: https://codepen.io/Crownedpride/project/editor/ZmbqRv/
If you want to know what it's going to be used for:
I'm currently writing a fantasy novel which I've got an artist drawing characters for. I want to display those characters on my own website via that setup I've made. There's roughly going to be 20 different characters that he'going to draw for me, although later there might be more depending if there'll be a Volume 2.
I'm looking forward to your replies.
ps: I'm really new to Jquery/js so please go easy on me >_<

Sticky div - stop scrolling at certain point

I have a fixed div that follows the page when it scrolls past the top of the page.
I would like it to stop scrolling once it reaches the bottom of a particular div. I am not great with javascript.
Basically needs to remove the class .affix. But it might need an offset so that it doesn't overlap into the layout below.
I have looked at other articles but the div starts off fixed whereas mine becomes fixed.
JSfiddle: https://jsfiddle.net/8t1ddL2h/
Javascript:
var stickySidebar = $('.sticky-sidebar').offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() > stickySidebar) {
$('.sticky-sidebar').addClass('affix');
}
else {
$('.sticky-sidebar').removeClass('affix');
}
});
Any help would be appreciated
Lee
Try this Fiddle
$(document).ready(function() {
var $sticky = $('.sticky-sidebar');
var $stickyrStopper = $('.other-content');
if (!!$sticky.offset()) { // make sure ".sticky" element exists
var generalSidebarHeight = $sticky.innerHeight();
var stickyTop = $sticky.offset().top;
var stickOffset = 0;
var stickyStopperPosition = $stickyrStopper.offset().top;
var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
var diff = stopPoint + stickOffset;
$(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns number
if (stopPoint < windowTop) {
$sticky.css({ position: 'absolute', top: diff });
} else if (stickyTop < windowTop+stickOffset) {
$sticky.css({ position: 'fixed', top: stickOffset });
} else {
$sticky.css({position: 'absolute', top: 'initial'});
}
});
}
});
You can also try it just add JavaScript. it will automatic calculate height of left panel. you need to change in css when it remove the css.
var othercon = $('.other-content').offset().top;
var sliderheight = $( ".sticky-sidebar" ).height();
$(window).scroll(function() {
if ($(window).scrollTop() >= othercon-sliderheight) {
$('.sticky-sidebar').removeClass('affix');
// need to change here according to your need
}
});

jQuery append (or appendTo) with Animation

I have a UL-LI e.g.
<ul>
<li id="1">item-1</li>
<li id="2">item-2</li>
<li id="3">item-3</li>
<li id="4">item-4</li>
</ul>
I would like to move one of the items to another position in the list. e.g. item-2 to AFTER item-4.
Normally I can do this by deleting the item and then appending it after another.
But I would like to do this to happen visually with animation. As in, item-2 descends to after item-4.
How can I achieve this?
IDs should not start with numbers...
$('#two').slideUp(500, function () {
$('#four').after(this);
$(this).slideDown(500);
});
Here is a demo: http://jsfiddle.net/jasper/8JFBA/
Or if you always want to add the element to the end:
$('#two').slideUp(500, function () {
$('ul').append(this);
$(this).slideDown(500);
});
Here is a demo: http://jsfiddle.net/jasper/8JFBA/1/
Update
Ok, so if you want the element to slide to it's new location here ya go:
//absolutely position the element and give it a top property so it doesn't go to the top of the container
$('#two').css({ position : 'absolute', top : $('#two').position().top });
//now get the offset to the bottom of the list by getting the top offset and height for the last list-item
var lastOffset = ($(this).children().last().position().top + $(this).children().last().height());
//now animate the element to the new position
$('#two').animate({ top : lastOffset }, 1000, function () {
//when the animation is done, re-add the element to the new position in the list and reset it's position and top values
$(this).appendTo('ul').css({ position : 'relative', top : 0 });
});
And a demo: http://jsfiddle.net/jasper/8JFBA/3/
Update
You can animate not only the element being moved to the end of the list but you can animate the rest of the list items as they move up:
var $LIs = $('ul').children(),
liHeight = 20;
$LIs.on('click', function () {
var index = ($(this).index()),
$LIsAfter = $LIs.filter(':gt(' + index + ')');
console.log(index);
$(this).css({ position : 'absolute', top : $(this).position().top });
$.each($LIsAfter, function (i) {
$(this).css({ position : 'absolute', top : ((i + index + 1) * liHeight) });
});
$(this).stop(true, true).animate({ top : (($LIs.length - 1) * liHeight)}, 1000, function () {
$(this).appendTo('ul').css({ position : 'relative', top : 0 });
});
$.each($LIsAfter, function (i) {
$(this).stop(true, true).animate({ top : ((index + i) * liHeight) }, 1000, function () {
$(this).css({ position : 'relative', top : 0 });
});
});
});
Here is a demo: http://jsfiddle.net/jasper/8JFBA/8/
This isn't quite complete, there is still a bug or two, but it should help get anyone started on the idea.
I tried to implement a smoother transition when you descend and below is my version..
You need to try out the demo to understand how it works.. Select value from the drop down and hit Descend to see the animation.
DEMO
Edit: Updated top position of $from before addClass('active') to start from the exact position and not top: 0px. Thanks to Jasper for finding this issue.
var $from = $('#from');
var $to = $('#to');
$('button').click (function () {
var from = $from.val();
var to = $to.val();
var $li = $('ul li');
var $fromEl = $('#' + from);
var $toEl = $('#' + to);
//only descending
if (from == to || $li.index($fromEl) > $li.index($toEl)) return;
var destX = $toEl.position().top;
$toEl.after('<li id="tmpLi2"></li>');
$('#tmpLi2').animate({height: $fromEl.outerHeight()}, 1000);
//add a blank li for smooth animation
$fromEl
.after('<li id="tmpLi1"> </li>')
.css ('top', $fromEl.position().top)
.addClass ('active' )
.animate({
top: (destX)
},
1000,
function() {
$toEl.after(this);
$('#tmpLi2').remove();
$(this).removeClass('active');
});
$('#tmpLi1').slideUp(function() { $(this).remove()});
});

javascript 'over-clicking' bug

I have a bug in Javascript where I am animating the margin left property of a parent container to show its child divs in a sort of next/previous fashion. Problem is if clicking 'next' at a high frequency the if statement seems to be ignored (i.e. only works if click, wait for animation, then click again) :
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
//roll margin back to 0
}
An example can be seen on jsFiddle - http://jsfiddle.net/ZQg5V/
Any help would be appreciated.
Try the below code which will basically check if the container is being animated just return from the function.
Working demo
$next.click(function (e) {
e.preventDefault();
if($contain.is(":animated")){
return;
}
var marLeft = $contain.css('margin-left'),
$this = $(this);
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
$contain.animate({
marginLeft: 0
}, function () {
$back.fadeOut('fast');
});
} else {
$back.fadeIn(function () {
$contain.animate({
marginLeft: "-=" + regWidth + "px"
});
});
}
if (marLeft > -combinedWidth) {
$contain.animate({
marginLeft: 0
});
}
});
Sometimes is better if you create a function to take care of the animation, instead of writting animation code on every event handler (next, back). Also, users won't have to wait for the animation to finish in order to go the nth page/box.
Maybe this will help you:
if (jQuery) {
var $next = $(".next"),
$back = $(".back"),
$box = $(".box"),
regWidth = $box.width(),
$contain = $(".wrap")
len = $box.length;
var combinedWidth = regWidth*len;
$contain.width(combinedWidth);
var currentBox = 0; // Keeps track of current box
var goTo = function(n) {
$contain.animate({
marginLeft: -n*regWidth
}, {
queue: false, // We don't want animations to queue
duration: 600
});
if (n == 0) $back.fadeOut('fast');
else $back.fadeIn('fast');
currentBox = n;
};
$next.click(function(e) {
e.preventDefault();
var go = currentBox + 1;
if (go >= len) go = 0; // Index based, instead of margin based...
goTo(go);
});
$back.click(function(e) {
e.preventDefault();
var go = currentBox - 1;
if (go <= 0) go = 0; //In case back is pressed while fading...
goTo(go);
});
}
Here's an updated version of your jsFiddle: http://jsfiddle.net/victmo/ZQg5V/5/
Cheers!
Use a variable to track if the animation is taking place. Pseudocode:
var animating = false;
function myAnimation() {
if (animating) return;
animating = true;
$(this).animate({what:'ever'}, function() {
animating = false;
});
}
Crude, but it should give you the idea.
Edit: Your current code works fine for me as well, even if I jam out on the button. On firefox.

Categories

Resources