I have created a script that animates the height of an element in 500ms.
The timer works fine but I am struggling to make the height increase consistently.
How do I animate the height smoothly within the time period? It jumps at the moment.
I want to replace the following with something smarter:
self.startHeight + 5
I imagine it has something to do with the speed and elapsed time?
https://jsfiddle.net/zrm7xena/1/
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
this.interval = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + 5; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.interval);
}
}, 16); //60FPS
};
animator.animate(document.getElementById('box'));
}());
Thanks in advance!
Carorus gave a great answer below. I have updated my jsfiddle so you can see the final code working:
https://jsfiddle.net/zrm7xena/8/
Typhoon posted a great link in relation to the browser FPS:
How to determine the best "framerate" (setInterval delay) to use in a JavaScript animation loop?
I would probably use request animation frame instead of a setInterval:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
Cheers all!
The harcoded 5 that you are using for the height increment doesn't allow the animation to complete the entire final height (200) in the time that you are setting (500ms), you need to calculate the height increment based on the final height, the animation time and the interval to make it consistent:
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.interval = 16;
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
//calculating height variation
self.deltaHeight = (animator.endHeight / animator.speed) * animator.interval;
this.intervalId = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + self.deltaHeight; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.intervalId);
}
}, animator.interval); //60FPS
};
animator.animate(document.getElementById('box'));
}());
Related
How can I make my progress bar show in increments based on my question number. Currently it completes to 100% after clicking the next question button. But, I am trying to let it increase in the increments of the question numbers and go backwards if the previous question button is clicked. The codepen with all the code is here. Thank you.
var i = 0;
function moveForward() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
function moveBackward() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
elem.innerHTML = width + "%";
}
}
}
}
///// UPDATED FUNCTION
function moveForward(i) {
console.log('i: ' + i);
var elem = document.getElementById("myBar");
switch(i) {
case 0:
elem.style.width = "33%";
elem.innerHTML = "33%";
break;
case 1:
elem.style.width = "66%";
elem.innerHTML = "66%";
break;
case 2:
elem.style.width = "100%";
elem.innerHTMl = "100%";
}
}
The reason it is completing after one click is that setInterval runs the function repetitively every x milliseconds. That means that your frame function runs every 10 milliseconds until it hits the if statement that clears the interval. Since your stop check only stops at width >= 100 it continues to expand until it is set to 100%.
In order to properly track the existing and next widths you will need to have a persistent variable in a global scope and you'll need to pass a target width to frame so that it knows when to actually stop
There are two other issues with your code. The first is that the previous button also increases the width rather than decreasing it, and the other issue is that every time you click the next or previous buttons it first resets the width to 10 and then increases it to 100.
I want to scroll to the bottom of the div when the page loads. I am using jQuery's animate() function this. The issue is that my code is working on desktop view, but if I change it to mobile view then my code is not working.
$(".chat-msg-list").animate({
scrollTop: $(".chat-msg-list").prop("scrollHeight")
}, 1000);
jQuery:
$(".chat-msg-list").animate({
scrollTop: $(".chat-msg-list").offset().top},
}, 1000);
Javascript:
function getElementY(query) {
return window.pageYOffset + document.querySelector(query).getBoundingClientRect().top
}
function doScrolling(element, duration) {
var startingY = window.pageYOffset
var elementY = getElementY(element)
// If element is close to page's bottom then window will scroll only to some position above the element.
var targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY
var diff = targetY - startingY
// Easing function: easeInOutCubic
// From: https://gist.github.com/gre/1650294
var easing = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }
var start
if (!diff) return
// Bootstrap our animation - it will get called right before next frame shall be rendered.
window.requestAnimationFrame(function step(timestamp) {
if (!start) start = timestamp
// Elapsed miliseconds since start of scrolling.
var time = timestamp - start
// Get percent of completion in range [0, 1].
var percent = Math.min(time / duration, 1)
// Apply the easing.
// It can cause bad-looking slow frames in browser performance tool, so be careful.
percent = easing(percent)
window.scrollTo(0, startingY + diff * percent)
// Proceed with animation as long as we wanted it to.
if (time < duration) {
window.requestAnimationFrame(step)
}
})
}
//Apply event handlers. Example of firing the scrolling mechanism.
doScrolling('#section1', 1000)
I want to change the position of div with for loop ..
I made an animation .. When i click a div ( circle ) it moves to a position that is being determined with Math.random() ..
I dont want to click the div to move to another position .
I want to use for loop method and i want div to move another position in every 2 seconds or some seconds ..
Do you have any advise .. Thanks
Click to see how it is
$(document).ready(function () {
$("#circle").click(function () {
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
});
});
Codepen
You don't really need a for-loop to do that. Instead of executing the code after clicking the div, you could just use the setInterval function instead:
$(document).ready(function () {
window.setInterval(function(){
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
}, 5000);
});
Just change the number 5000 to adjust the time that should pass before the code is executed again (1000ms is 1 second).
On Codepen
I am trying to make this function works only when the screen size is above 1024px.
//Parallax background image
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};$(window).bind('scroll', update); update();
Here is what I have tried to do:
//Parallax background image
var velocity = 0.5;
$(window).on("ready resize", function() {
if ($(window).width() < 770) {
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};});$(window).bind('scroll', update); update();
I really don't know what I am doing wrong...
You haven't stated what the problem you're coming across is. If it's "my code doesn't work", then perhaps you should check your syntax first. Your braces are messed up.
//Initialize velocity and empty update function
var velocity = 0.5;
var update = function () {};
//When window is ready (content loaded) OR resized, execute the following function
$(window).on("ready resize", function () {
if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger
update = function () { //Set update to run this function when executed.
var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/
//For each element with 'parallax' class, execute the following function
$('.parallax').each(function () {
var $element = $(this); //Get the current parallax-classed element
var height = $element.height(); //Save the current height of this element
//Set the CSS of this parallax-classed element set the background position
$(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px');
});
};
} else { //Execute if screen width is < 1024px
update = function () {}; //Set update to do nothing
}
});
//When window is scrolled through, run the update function
$(window).bind('scroll', update);
//update();
Last line is unnecessary, as resize will handle function value, and scroll will handle the execution.
You were missing a + or - within the background-position setting.
So for example, if the result of your Math.round() was "30", then Javascript would interpret that line as $(this).css('background-position', '40%30px'); which obviously would cause issues. I'm sure you wanted it to say something like $(this).css('background-position', '40% + 30px');.
I built a kind of chat in JS and then I wanted that when I got new message the chat automatically scrolled down (with animation...). Everything worked beautifully, but after the animation stopped the user couldn't scroll by himself; the chat automatically scrolled to the end.
So this is the code :
<!-- language:lang-js -->
var height = 1;
window.setInterval(function() {
var elem = document.getElementById('chat');
elem.scrollTop = height;
if (elem.scrollheight < height) {
clearInterval(this);
}
height += 2;
}, 50);
the clearInterval function expects a number. Using that should make it work correctly. You also have many syntax errors.
var intervalReference = window.setInterval(function() {
var elem = document.getElementById('chat');
elem.scrollTop = height;
if (elem.scrollHeight < height) {
clearInterval(intervalReference);
}
height += 2;
}, 50);
you should make a var holding the interval like this :
var height = 1;
var interval = window.setInterval( animate, 50 );
function animate() {
var elem = document.getElementById('chat');
elem.scrollTop = height;
if (elem.scrollHeight < height) {
clearInterval( interval );
}
height += 2;
}
this should work fine