I'm trying to create a slider with an image gallery and to make it scroll smooth using the requestAnimationFrame.
It works almost perfect except one thing. If you slide more then 2 times in any direction the scroll speeds up and it looks bad. I would like to have the same speed every time I slide to right or left.
Can anyone give me a hint of how to do that?
var currentPos = -200;
var incrementer = .05;
var id;
function scrollNext() {
incrementer += 1;
currentPos = Math.pow(1.05, incrementer);
item.scrollLeft += currentPos;
id = requestAnimationFrame(scrollNext);
if (!curr_slide.nextElementSibling) {
if (item.scrollLeft >= curr_slide.offsetLeft) {
item.scrollTo(curr_slide.offsetLeft, 0);
cancelAnimationFrame(id);
}
if (item.scrollLeft < curr_slide.offsetLeft) {
item.scrollTo(curr_slide.offsetLeft, 0);
cancelAnimationFrame(id);
}
} else {
if (item.scrollLeft >= curr_slide.nextElementSibling.offsetLeft) {
item.scrollTo(curr_slide.nextElementSibling.offsetLeft, 0);
cancelAnimationFrame(id);
}
}
}
scrollNext();
curr_slide.nextElementSibling.classList.add('activeSlide');
curr_dot.nextElementSibling.classList.add('currentDot');
Related
So, i've coded this canvas animation and I would like the shape to move faster though when doing so the shapes desync.
When I increment the values show below, so that the shapes would faster, they do so but eventually move away from eachother and desync.
if (this.dir[i][j] === 'downright') { //go down and right
this.boxLines[i][j].y += 1;
this.boxLines[i][j].x += 1;
}
if (this.dir[i][j] === 'downleft') { //go down and left
this.boxLines[i][j].y += 1;
this.boxLines[i][j].x -= 1;
}
if (this.dir[i][j] === 'upright') { //go up and right
this.boxLines[i][j].y -= 1;
this.boxLines[i][j].x += 1;
}
if (this.dir[i][j] === 'upleft') { //go up and left
this.boxLines[i][j].y -= 1;
this.boxLines[i][j].x -= 1;
}
Any way to fix that or could i go about it some other way?
Link to jsfiddle: https://jsfiddle.net/frankpettersson/nqmy3fkd/7/
I ran across an issue where my code worked just fine in Chrome but in Safari it began to stutter. I read somewhere that "Safari caps intervals at 1000ms and then adds its own exponential delay, doubling every iteration." That being said I am trying to change my code to work both on Safari and Chrome using requestAnimationFrame but am having issues wrapping my head around the subject.
Essentially what I am trying to do is ease a div across a page with each click using requestAnimationFrame instead of setInterval.
Any guidance would be appreciated.
Here is the Javascript:
let progressAvatar = document.querySelector('.box');
progressAvatar.addEventListener('click', checkClick);
var clicks = 0;
function checkClick() {
clicks += 1;
if (clicks == 1) {
startingLocationOfAvatar();
} else if (clicks == 2) {
locationOfAvatar();
}
}
function startingLocationOfAvatar() {
let speed = 10;
// Initial location of Avatar
let pos = 0;
// Ending location of Avatar
let progressBarWidthDivided = 53;
let id = setInterval(frame, speed);
function frame() {
if (pos == progressBarWidthDivided) {
clearInterval(id);
} else {
pos++;
progressAvatar.style.marginLeft = pos + "px";
}
}
}
// Move the avatar based on its previous location
function locationOfAvatar() {
let speed = 10;
// Pos becomes last location of movePixels
let pos = 53;
let id = setInterval(frame, speed);
// movePixels adds last location by its new location
let movePixels = pos * 2;
function frame() {
if (pos == movePixels) {
clearInterval(id);
} else {
pos++;
progressAvatar.style.marginLeft = pos + "px";
}
}
}
Here is the Html:
<div class="box">
</div>
Here is the Css:
.box {
height: 100px;
width: 100px;
background-color:red;
}
Lastly here is a jsfiddle:
Move Div Across Screen
I will let experts answer, but as a 2 weeks coding noob this is what i know, you can compile all individual animation functions into a grand Animation function. And call that function with request animation frame. Trying to make a sensible game myself, i have totally given up on manipulating css values and coding in pure Javascript.
Note, dependent where you will put your mini-functions - the photos/graphical items will display either on top or under eachother visually.
It should look something like this:
function drawEverything(){
context.clearRect(0,0,width,height);
context.save();
draw();
draw1();
draw2();
context.restore();
requestAnimationFrame(drawEverything);
}
requestAnimationFrame(drawEverything);
I am looking for a way to only scroll horizontal OR vertical inside a html table view while maintaining a header and row that is always visible. Preferably I would like something similar to this but in pure Javascript without ember or coffeescript. I prefer not to use the ember-table because the rest of my project is not based on ember and I am unfamiliar with it.
So I started out with something similar here. It has the benefit of having the header row and column but it scrolls in both the horizontal direction as well as the vertical direction. The difference between this example and the first one is that the addepar table only scrolls in one direction. Which is a more calm user experience.
I have been looking into possible ways to get to where I want. The first part seems to be to check in which direction the user is scrolling. Such a thing can be done with jQuery;
var previousScrollvertical = 0,
previousScrollHorizontal = 0;
$(window).scroll(function(){
var currentVerticalScroll = $(this).scrollTop(),
currentHorizontalScroll = $(this).scrollLeft();
if(currentVerticalScroll==previousScrollvertical) {
if (currentHorizontalScroll > previousScrollHorizontal){
console.log('Right');
} else {
console.log('left');
}
} else if(currentHorizontalScroll==previousScrollHorizontal) {
if (currentVerticalScroll > previousScrollvertical){
console.log('down');
} else {
console.log('up');
}
}
previousScrollHorizontal = currentHorizontalScroll;
previousScrollvertical =currentVerticalScroll;
});
This snippet of code works on any website that has jQuery loaded. You can try it out from the console.
But from here I seem to be stuck. Is it possible to block a scroll direction with jQuery? Is there an easier way to achieve this? Should I be considering a completely different route?
The short answer is to use jQuery's scrollTop or scrollLeft to set the scroll of the direction you want to block back to what it was before.
I've created a quick example that shows how one might do that in practice:
Live Demo
var $container = $('.table-container');
var $table = $container.find('table');
var previousScroll = [0, 0];
var correction = false;
// Adjust the threshold to a larger number if you'd like it
// to take longer to switch between horizontal and vertical
// scrolling
var threshold = 10;
var direction;
var directionTimeout;
$container.on('scroll', function (event) {
if (!correction) {
var element = event.currentTarget,
$element = $(event.currentTarget),
x = element.scrollLeft,
y = element.scrollTop;
var diff = [
Math.abs(x - previousScroll[0]),
Math.abs(y - previousScroll[1])
];
correction = true;
if (!direction) {
if (diff[0] > diff[1]) {
direction = 'horizontal';
} else if (diff[0] < diff[1]) {
direction = 'vertical';
} else {
direction = 'vertical';
}
}
if (direction === 'horizontal') {
$element.scrollTop(previousScroll[1]);
previousScroll = [x, previousScroll[1]];
} else {
$element.scrollLeft(previousScroll[0]);
previousScroll = [previousScroll[0], y];
}
clearTimeout(directionTimeout);
directionTimeout = setTimeout(function () {
direction = null;
}, threshold);
} else {
correction = false;
}
});
Can I get some help with animating elements on a canvas? I would like to get the elements already drawn on the canvas and "move" them off the canvas and display the new elements. My functions are in javascript and work nicely. I would just like to add animation. TIA.
just have an event handler control the left of the style for that canvas's id and then specify a loop to have it change or move to the left/right based on time.
(function() {
var speed = 10,
movePic = function(moveBy) {
var el = document.getElementById("animationStyle"),
left = el.offsetLeft
if ((moveBy > 0 && left > 399) || (moveBy < 0 && left < 51)) {
clearTimeout(timer);
timer = setInterval(function () {
movePic(moveBy * -1);
}, speed);
}
el.style.left = left + moveBy + "px";
};
var timer = setInterval(function () {
movePic(3)
}, speed);
}());
This would move it back and forth, this is an example that should help you get started.
I'm wondering if there is a simple way to make use of JavaScript (probably jQuery too?) in order to make the contents of a fixed-height div element scroll infinitely up and down (top, bottom, top, bottom, etc) when the page loads and without any user input or manipulation?
Thanks ahead of time, any input is greatly appreciated as I am hardly mediocre with JavaScript.
With pure js you can do something like this:
var scroller = document.getElementById('scroller');
var delta = 15;
var lastSc;
//console.log(scroller.scrollTop, scrollHeight);
setInterval(function(){
var sc = scroller.scrollTop + delta;
scroller.scrollTop = sc;
if (scroller.scrollTop === lastSc){
delta = delta*(-1);
}
lastSc = scroller.scrollTop;
}, 10);
Here is demo
Edit: updated demo
Here is something I've just written, using jQuery:
var speed = 100; //smaller means faster
var offset = 5; //bigger means more text will be "scrolled" every time
function ScrollMyDiv() {
var myDiv = $("#MyDiv");
var direction = myDiv.attr("scroll_dir") || "";
var lastScrollTop = parseInt(myDiv.attr("last_scroll_top") || "0", 10);
if (direction.length === 0) {
myDiv.attr("scroll_dir", "down");
direction = "down";
}
var top = myDiv.scrollTop();
myDiv.attr("last_scroll_top", top + "")
if (direction === "down") {
if (top > 0 && lastScrollTop === top)
myDiv.attr("scroll_dir", "up");
top += offset;
} else {
if (top <= 0)
myDiv.attr("scroll_dir", "down");
top -= offset;
}
myDiv.scrollTop(top);
window.setTimeout(ScrollMyDiv, speed);
}
$(document).ready(function() {
ScrollMyDiv();
});
Live test case: http://jsfiddle.net/HmfNJ/1/
Basically, it will start by scrolling down (adding to the scrollTop) then when it identify it reached the bottom by seeing the scrollTop remains the same, it will change direction and start scroll up.
Thanks for the replies but I found my answer elsewhere. Here's what I ended up using: http://jsbin.com/onohan/3/edit#preview
It had a couple of small problems but I at least knew enough about basic JavaScript to fix them. Hopefully this will benefit someone in the future. :)
To get a smooth transition for scroll to bottom this is VanillaJS code that works well with me
var delta = 0.6, interval;
interval = setInterval(function(){
window.scrollBy(0, delta);
}, 20);
To clear the Interval you can run
clearInterval(interval);