Simple animation change height without jquery - javascript

I need simple animation on simple js. I think jquery too much for that. I need to increase or decrease the height of the block by pressing the buttons, but this work only on Opera (.
Example
function global_animate(element, property_to_map, duration, callback) {
duration = duration || 1000;
var delta = function (a) { return a; };
var start = new Date().getTime();
var property_from_map = {};
var property_units_map = {};
for (var property in property_to_map) {
property_from_map[property] = window.getComputedStyle(element, null)[property] || element.currentStyle[property];
property_units_map[property] = parseUnits(property_from_map[property]);
property_from_map[property] = parseInt(property_from_map[property]);
property_to_map[property] = parseInt(property_to_map[property]);
}
function parseUnits(a) {
try {
return a.match(/^\d+(\w{2}|%);?$/i)[1];
} catch (e) {
return "";
}
}
setTimeout(function() {
var now = (new Date().getTime()) - start;
var progress = now / duration;
for (var property in property_to_map) {
var result = (property_to_map[property] - property_from_map[property]) * delta(progress) + property_from_map[property];
element.style[property] = result.toFixed(2) + property_units_map[property];
}
if (progress < 1)
setTimeout(arguments.callee, 10);
else
if (typeof callback == 'function')
callback();
}, 10);
}

you need to change the regexp from
alert("23.2px".match(/^\d+(\w{2}|%);?$/i));​ // alert null
to something like this
alert("23.2px".match(/^\d+\.*\d*(\w{2}|%);?$/i));​ // alert ["23.2px", "px"]

I think the problem lies in your regex: a.match(/^\d+(\w{2}|%);?$/i)[1];. The second time it runs it does’t catch the units properly.
If I hard code the units to 'px', it works for me (in chrome): http://jsfiddle.net/9DCA5/5/
Maybe you can debug from there?

Method getComputedStyle() is not supported in IE, which uses the "currentStyle" property instead.

Related

How to compare executed function output correctly?

So what im trying to do in general is -> get a moment when user scrolls up really fast on mobile device -> some text executed in console (for example)
What I have is 2 simple functions:
//calculate scroll speed
var mobileScroll = (function(){
var last_position, new_position, timer, delta, delay = 50;
function clear() {
last_position = null;
delta = 0;
}
clear();
return function(){
new_position = window.scrollY;
if ( last_position !== null ){
delta = new_position - last_position;
}
last_position = new_position;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
Then I'm trying to compare the outputted value with some static number like this:
var scrolledFast = function scrolledFast(e) {
console.log("scroll: " + mobileScroll());//works fine
console.log(mobileScroll());//always 0
//if statement does not work
if(document.body.classList.contains('on-mobile-device') && mobileScroll() < -200 ){
console.log('Scrolled up fast enough');
}
}
document.addEventListener('scroll', scrolledFast);
The problem is that I don't understand why I can get the outputted value like this:
console.log("scroll speed: " + mobileScroll()); // I see "scroll: -100" or some other value
But when I'm trying to get something like:
console.log(mobileScroll());
//or
var mobScrollSpeed = mobileScroll();
console.log(mobScrollSpeed);
it is always 0...

Image animation with speed control

We have some problem with our image animation with speed control.
It make use of a timeout to change the image, but we want to change the timeout value with a slider, but for some sort of reason, it doesn't work. Can someone help us out ?
We have a Jfiddle here: http://jsfiddle.net/Kbroeren/fmd4xbew/
Thanks! Kevin
var jArray = ["http://www.parijsalacarte.nl/images/mickey-mouse.jpg", "http://www.startpagina.nl/athene/dochters/cliparts-disney/images/donad%20duck-106.jpg", "http://images2.proud2bme.nl/hsfile_203909.jpg"];
var image_count = 0;
function rollover(image_id, millisecs) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
rollover("img1", 200);
$(function () {
var value;
var $document = $(document),
$inputRange = $('input[type="range"]');
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value,
output = element.parentNode.getElementsByTagName('output')[0];
output.innerHTML = value;
}
for (var i = $inputRange.length - 1; i >= 0; i--) {
valueOutput($inputRange[i]);
};
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
rollover("img1", 200);
});
// end
$inputRange.rangeslider({
polyfill: false
});
});
You keep creating more and more infinite function calls without stopping them.
After you call your function the first time, it keeps calling itself.
then you call it again with different interval (millisecs) and it will also start call itself....
You can try two different approach.
1.Use setInterval instead of setTimeout. Use clearInterval to clear the interval before setting it with a new value.
/// Call animation() every 200 ms
var timer = setInterval("Animation()",200);
function ChageSpeed(miliseces){
///Stop calling Animation()
clearInterval(timer);
/// Start calling Animation() every "miliseces" ms
timer = setInterval("Animation()",miliseces);
}
function Animation(){
/// Animation code goes here
}
2.Or, Instead, Set your interval as a global variable (not cool) and just change it value when the user want to change the animation speed.
var millisecs = 200;
function rollover(image_id) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
millisecs = YourNewValue;
});

Pure JavaScript fade in function

Hi friends i want to fade in a div when i click on another div and for that i am using following code. Code1 works fine but i require to use the Code2.
I know there is jQuery but i require to do this in JavaScript
Can you guide me that what kind of mistake i am doing or what i need change...
Code1 --- Works Fine
function starter() { fin(); }
function fin()
{
for (i = 0; i <= 1; i += 0.01)
{
i=Math.round(i*100)/100;
setTimeout("seto(" + i + ")", i * 1000);
}
}
function seto(opa)
{
var ele = document.getElementById("div1");
ele.style.opacity = opa;
}
Code2 --- Does not work
function starter()
{
var ele = document.getElementById("div1");
fin(ele);
}
function fin(ele)
{
for (i = 0; i <= 1; i += 0.01)
{
i=Math.round(i*100)/100;
setTimeout("seto(" + ele + "," + i + ")", i * 1000);
}
}
function seto(ele,opa)
{
ele.style.opacity = opa;
}
Based on this site
EDIT-1
Added the functionality so that user can specify the animation duration(#Marzian comment)
You can try this:
function fadeIn(el, time) {
el.style.opacity = 0;
var last = +new Date();
var tick = function() {
el.style.opacity = +el.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
var el = document.getElementById("div1");
fadeIn(el, 3000); //first argument is the element and second the animation duration in ms
DEMO
Update:
It seems that people enjoy my minimalistic and elegant approach, Updated for 2022:
No need for complex mechanisms. Just use CSS, which has it out of the box and has better performance overall.
Basically you achieve it with CSS by setting a transition for the opacity. In JavaScript that would be:
const div = document.querySelector('#my-div');
div.style.transition='opacity 1s';
and as a trigger you just set opacity to 0:
div.style.opacity=0;
This will create a 1 second fade out effect and you can use the trigger anywhere. The inverse can also be done to achieve a fade in effect.
Here's a working example:
const div = document.querySelector('#my-div');
div.style.transition='opacity 1s';
// set opacity to 0 -> fade out
setInterval(() => div.style.opacity=0, 1000);
// set opacity to 1 -> fade in
setInterval(() => div.style.opacity=1, 2000);
#my-div { background-color:#FF0000; width:100%; height:100%; padding: 10px; color: #FFF; }
<div id="my-div">Hello!</div>
Seems like your attempting to convert your element, to a string. Try this instead
function starter()
{
var ele = document.getElementById("div1");
fin(ele);
}
function fin(ele)
{
for (i = 0; i <= 1; i += 0.01)
{
i=Math.round(i*100)/100;
setTimeout(function() { setto(ele,i); }, i * 1000);
}
}
function seto(ele,opa)
{
ele.style.opacity = opa;
}
What happens here is, that i call a anonnymous function when the timer hits, and from that function, execute my functioncall to setto.
Hope it helps.
Jonas
The problem here is you are using the pass-a-string method of using setTimeout. Which is basically just a hidden eval.
It's worth noting that this is a bad practice, slow performer, and security risk.
(see questions such as this: setTimeout() with string or (anonymous) function reference? speedwise)
The reason this is causing your problem is because "seto(" + ele + "," + i + ")" is going to evaluate to "seto('[object HTMLDivElement]', 1)". You really want to pass reference to the ele object -- but the value's being cast to a string when you tried concatenating an object onto a string. You can get around this by using the pass-a-function method of using setTImeout.
setTimeout(function() { seto(ele, i); }, i * 1000);
I believe making this change will make your Code2 behavior equivalent to Code1.
Below are the complete answers to my question
ANS1 --- DEMO
function fin() {
var i = 0;
var el = document.getElementById("div1");
fadeIn(el,i);
}
function fadeIn(el,i) {
i = i + 0.01;
seto(el,i);
if (i<1){setTimeout(function(){fadeIn(el,i);}, 10);}
}
function seto(el,i) {
el.style.opacity = i;
}
ANS2 --- DEMO
function fin(){
var i = 0;
var el = document.getElementById("div1");
fadeIn(el,i);
}
function fadeIn(el,i) {
var go = function(i) {
setTimeout( function(){ seto(el,i); } , i * 1000);
};
for ( i = 0 ; i<=1 ; i = i + 0.01) go(i);
}
function seto(el,i)
{
el.style.opacity = i;
}
My version
function fadeIn($element){
$element.style.display="block";
$element.style.opacity=0;
recurseWithDelayUp($element,0,1);
}
function fadeOut($element){
$element.style.display="block";
$element.style.opacity=1;
recurseWithDelayDown($element,1,0);
}
function recurseWithDelayDown($element,startFrom,stopAt){
window.setTimeout(function(){
if(startFrom > stopAt ){
startFrom=startFrom - 0.1;
recurseWithDelayDown($element,startFrom,stopAt)
$element.style.opacity=startFrom;
}else{
$element.style.display="none"
}
},30);
}
function recurseWithDelayUp($element,startFrom,stopAt){
window.setTimeout(function(){
if(startFrom < stopAt ){
startFrom=startFrom + 0.1;
recurseWithDelayUp($element,startFrom,stopAt)
$element.style.opacity=startFrom;
}else{
$element.style.display="block"
}
},30);
}
function hide(fn){
var hideEle = document.getElementById('myElement');
hideEle.style.opacity = 1;
var fadeEffect = setInterval(function() {
if (hideEle.style.opacity < 0.1)
{
hideEle.style.display='none';
fn();
clearInterval(fadeEffect);
}
else
{
hideEle.style.opacity -= 0.1;
}
}, 20);
}
function show(){
var showEle = document.getElementById('myElement');
showEle.style.opacity = 0;
showEle.style.display='block';
var i = 0;
fadeIn(showEle,i);
function fadeIn(showEle,i) {
i = i + 0.05;
seto(showEle,i);
if (i<1){setTimeout(function(){fadeIn(showEle,i);}, 25);}
}
function seto(el,i)
{
el.style.opacity = i;
}
}
hide(show);
I just improved on laaposto's answer to include a callback.
I also added a fade_out function.
It could be made more efficient, but it works great for what i'm doing.
Look at laaposto's answer for implementation instructions.
You can replace the JS in his fiddle with mine and see the example.
Thanks laaposto!
This really helped out for my project that requires zero dependencies.
let el = document.getElementById( "div1" );
function fade_in( element, duration, callback = '' ) {
element.style.opacity = 0;
let last = +new Date();
let tick = function() {
element.style.opacity = +element.style.opacity + ( new Date() - last ) / duration;
last = +new Date();
if ( +element.style.opacity < 1 )
( window.requestAnimationFrame && requestAnimationFrame( tick ) ) || setTimeout( tick, 16 );
else if ( callback !== '' )
callback();
};
tick();
}
function fade_out( element, duration, callback = '' ) {
element.style.opacity = 1;
let last = +new Date();
let tick = function() {
element.style.opacity = +element.style.opacity - ( new Date() - last ) / duration;
last = +new Date();
if ( +element.style.opacity > 0 )
( window.requestAnimationFrame && requestAnimationFrame( tick ) ) || setTimeout( tick, 16 );
else if ( callback !== '' )
callback();
};
tick();
}
fade_out( el, 3000, function(){ fade_in( el, 3000 ) } );
Cheers!

Javascript gradual width increase

I'm trying to gradually increase the elements of 2 id's in javascript using a Timeout. I can get one working but when trying to call another element into the same function it only does one iteration then crashes after the first recursive call.
I'm passing two id's for the elements. and I want the left element to gradually increase while the right element gradually increases in width.
Heres what ive got
function grow(elementL, elementR)
{
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL = htL + 5;
var movementR = htR - 5;
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
if (movementL > 1000) {
clearTimeout(loopTimer);
return false;
}
var loopTimer = setTimeout('grow(\''+elementL+','+elementR+'\')',50);
}
You could simplify this (removing the script-generation) by using setInterval -- this repeats the function call until you cancel it.
function grow(elementL, elementR)
{
var loopTimer = setInterval(function() {
if (!growStep(elementL, elementR)) {
clearInterval(loopTimer);
}
}, 50);
}
function growStep(elementL, elementR) {
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL = htL + 5;
var movementR = htR - 5;
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
if (movementL > 1000) {
return false;
}
return true;
}
(Fiddle)
Edit
Yeah, I guess the only problem with the OP code is that it passes a string to setTimeout, rather than the function itself:
var loopTimer = setTimeout(function() {
grow(elementL, elementR);
},50);
setTimeout('grow(\''+elementL+','+elementR+'\')',50)
would need to be
setTimeout('grow(\''+elementL+'\',\''+elementR+'\')',50)
// ^^ ^^
to work. But don't do that. Pass a function expression to setTimeout:
setTimeout(function() {
grow(elementL, elementR);
}, 50)

Setting a time for flicker animation on img

I'm using this code to make my logo flicker on my website. But It becomes annoying when it continues to flicker while browsing, how can I set a time to allow it to flicker for something like the first 15seconds on page load, then stops?
JS code I'm using:
$(document).ready(
function(){
var t;
const fparam = 100;
const uparam = 100;
window.flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = setTimeout('window.unflickr()',uparam);
}
else
t = setTimeout('window.flickr()',fparam);
}
window.unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = setTimeout('window.flickr()',fparam);
}
else
t = setTimeout('window.unflickr()',uparam);
}
t = setTimeout('window.flickr()',fparam);
});
You could have a counter, which you then use to decide whether you want to set another timeout. As a side note, you should never add functions to window and then passing a string to setTimeout. Always just pass the function itself:
$(document).ready(function(){
var t;
var amount = 0;
const fparam = 100;
const uparam = 100;
function timeout(f, t) { // this function delegates setTimeout
if(amount++ < 150) { // and checks the amount already (un)flickered
setTimeout(f, t); // (150 * 100 ms = 15 s)
}
}
var flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = timeout(unflickr,uparam);
}
else
t = timeout(flickr,fparam);
};
var unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = timeout(flickr,fparam);
}
else
t = timeout(unflickr,uparam);
};
t = timeout(flickr,fparam);
});
I see you're using jquery, you could use the following, if I remember correctly, all the stuff I use below has been in jquery since 1.0, so you should be good:
counter = 1;
function hideOrShow(){
$(".classToSelect").animate({"opacity": "toggle"}, 100);
counter = counter +1;
if (counter >= 21) clearInterval(flickerInterval);
}
flickerInterval = setInterval(hideOrShow, 100);
Change the selector, animation duration, and variable names to whatever you fancy/need.

Categories

Resources