setInterval animation - javascript

http://jsfiddle.net/vzBZB/5/
(function(){
var i = 1;
var start = true;
setInterval(function(){
if (i>0&&start){
var o = $("#box").css("opacity");
var s = parseFloat(o) - 0.1;
$("#box").css("opacity", s.toString());
i = s;
}
else {
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if (i==1) start = true;
}
}, 100);
})();
This code does simple animation - it goes from opacity 1 to 0 and back to 1. But i would like to perform this cycle infinitely. i used if (i==1) start = true; but it doesnt help. how do i fix? Second question: when it stops opacity is 1.1. Why? How do i fix?

How about just set "start" back to true when you're done fading back in. Such as:
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if(s >= 1) start = true; //Reset for next loop
Here's my working example: http://jsfiddle.net/vzBZB/8/

You may find it easier to simply use the callback parameter of .fadeToggle recursively. See my update to your jsfiddle: http://jsfiddle.net/vzBZB/6/.

You arent setting start back to true when it gets back to full opacity...
add this
if (o >= 1){
start=true;
}
full code:
(function(){
var i = 1;
var start = true;
setInterval(function(){
if (i>0&&start){
var o = $("#box").css("opacity");
var s = parseFloat(o) - 0.1;
$("#box").css("opacity", s.toString());
i = s;
}
else {
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if (o >= 1){
start=true;
}
}
}, 100);
})();

Related

Stop loop in typewriter effect using JS

I am so close to the perfect typewriter effect for my website - mostly thanks to the support of your fantastic input here! What I'm looking for is a slight variation of the typewriter effect below: To have the last line of text remain on the screen rather than being erased (but not, as instructed in another post, the ENTIRE text, only the LAST LINE).
So ideally, the first line would build up, then get erased, then the second one would build up, then get erased as well, and then, finally, the third one would build up and remain on screen (while the cursor still continues to blink). If you could help me figure out this modification, I'd really be eternally grateful! Thank you a million in advance!
PS: If there is any chance to add a DELAY as well so the very first line starts building up after e.g. 5 seconds (in which only the cursor blinks), this would be the cherry on the icing! :-)
PPS: Here's the link to the original code:
consoleText(['Hello World.', 'Console Text', 'Made with Love.'], 'text',['tomato','rebeccapurple','lightblue']);
function consoleText(words, id, colors) {
if (colors === undefined) colors = ['#fff'];
var visible = true;
var con = document.getElementById('console');
var letterCount = 1;
var x = 1;
var waiting = false;
var target = document.getElementById(id)
target.setAttribute('style', 'color:' + colors[0])
window.setInterval(function() {
if (letterCount === 0 && waiting === false) {
waiting = true;
target.innerHTML = words[0].substring(0, letterCount)
window.setTimeout(function() {
var usedColor = colors.shift();
colors.push(usedColor);
var usedWord = words.shift();
words.push(usedWord);
x = 1;
target.setAttribute('style', 'color:' + colors[0])
letterCount += x;
waiting = false;
}, 1000)
} else if (letterCount === words[0].length + 1 && waiting === false) {
waiting = true;
window.setTimeout(function() {
x = -1;
letterCount += x;
waiting = false;
}, 1000)
} else if (waiting === false) {
target.innerHTML = words[0].substring(0, letterCount)
letterCount += x;
}
}, 120)
window.setInterval(function() {
if (visible === true) {
con.className = 'console-underscore hidden'
visible = false;
} else {
con.className = 'console-underscore'
visible = true;
}
}, 400)
}
Here's my take on it:
// function([string1, string2], target id, [color1,color2], initial pause, final pause)
consoleText(['Hello World.', 'Console Text', 'Made with Love.'], 'text',['tomato','rebeccapurple','lightblue'], 5000, 500000);
function consoleText(words, id, colors, initialPause, finalPause) {
if (colors === undefined) colors = ['#fff'];
var visible = true;
var con = document.getElementById('console');
var letterCount = 1;
var x = 1;
var initialCount = 0;
var waiting = false;
var target = document.getElementById(id);
var justStarted = true;
target.setAttribute('style', 'color:' + colors[0]);
window.setInterval(function() {
if(initialCount < initialPause){
initialCount += 120;
} else if (letterCount === 0 && waiting === false) {
waiting = true;
target.innerHTML = words[0].substring(0, letterCount);
window.setTimeout(function() {
var usedColor = colors.shift();
var usedWord = words.shift();
x = 1;
target.setAttribute('style', 'color:' + colors[0]);
letterCount += x;
waiting = false;
}, 1000);
} else if (letterCount === words[0].length + 1 && waiting === false) {
waiting = true;
window.setTimeout(function() {
x = -1;
letterCount += x;
waiting = false;
}, words.length === 1 ? finalPause : 1000);
} else if (waiting === false) {
target.innerHTML = words[0].substring(0, letterCount);
letterCount += x;
}
}, 120);
window.setInterval(function() {
if (visible === true) {
con.className = 'console-underscore hidden';
visible = false;
} else {
con.className = 'console-underscore';
visible = true;
}
}, 400);
}

Parallax scroll not working on mobile

Hi there I have a parallax effect scroll on my website, it is all working good on desktop but mobile device it is not working properly when I attempt to even scroll/swipe down the page.
Here is the javascript:
var ticking = false;
var isFirefox = /Firefox/i.test(navigator.userAgent);
var isIe = /MSIE/i.test(navigator.userAgent) || /Trident.*rv\:11\./i.test(navigator.userAgent);
var scrollSensitivitySetting = 30;
var slideDurationSetting = 800;
var currentSlideNumber = 0;
var totalSlideNumber = $('.background').length;
function parallaxScroll(evt) {
if (isFirefox) {
delta = evt.detail * -120;
} else if (isIe) {
delta = -evt.deltaY;
} else {
delta = evt.wheelDelta;
}
if (ticking != true) {
if (delta <= -scrollSensitivitySetting) {
ticking = true;
if (currentSlideNumber !== totalSlideNumber - 1) {
currentSlideNumber++;
nextItem();
}
slideDurationTimeout(slideDurationSetting);
}
if (delta >= scrollSensitivitySetting) {
ticking = true;
if (currentSlideNumber !== 0) {
currentSlideNumber--;
}
previousItem();
slideDurationTimeout(slideDurationSetting);
}
}
}
function slideDurationTimeout(slideDuration) {
setTimeout(function () {
ticking = false;
}, slideDuration);
}
var mousewheelEvent = isFirefox ? 'DOMMouseScroll' : 'wheel';
window.addEventListener(mousewheelEvent, _.throttle(parallaxScroll, 60), false);
function nextItem() {
var $previousSlide = $('.background').eq(currentSlideNumber - 1);
$previousSlide.css('transform', 'translate3d(0,-130vh,0)').find('.content-wrapper1').css('transform', 'translateY(40vh)');
currentSlideTransition();
}
function previousItem() {
var $previousSlide = $('.background').eq(currentSlideNumber + 1);
$previousSlide.css('transform', 'translate3d(0,30vh,0)').find('.content-wrapper1').css('transform', 'translateY(30vh)');
currentSlideTransition();
}
function currentSlideTransition() {
var $currentSlide = $('.background').eq(currentSlideNumber);
$currentSlide.css('transform', 'translate3d(0,-15vh,0)').find('.content-wrapper1').css('transform', 'translateY(15vh)');
;
}
Your help would be appreciated thank you!

Slideshow in JavaScript not working

Okay I successfully created a basic slideshow but I wanted to add more effects and such to make it look more realistic. I am doing some coding but I don't know what is wrong. I end up crashing my MOZILLA everytime I run the script. Can anyone help me do this correctly? And not to mention I don't want any kind of jQuery modification to my code
JavaScript
var img = new Array("a.jpg","b.jpg","c.jpg");
var len = img.length - 1;
var pos = 0;
function slid(e){
pos = pos + e;
if(pos < 0)
{
pos = len;
}
if(pos > len)
{
pos = 0;
}
var a = 1;
var i = 1;
while(i<=50)
{
function op(a) {
a -= 0.02;
if(a < 0)
{
a = 1;
}
document.getElementById("slide").style.opacity = a;
}
i++;
}
document.getElementById("slide").src = img[pos];
return false;
};
and yeah it's not fading(in this case changing opacity) help me on that too?
Take a look here:
while(i<=50)
{
function op(a) {
a -= 0.02;
if(a < 0)
{
a = 1;
}
document.getElementById("slide").style.opacity = a;
}
}
You are not incrementing your 'i' counter variable, resulting in an infinite loop, and hence browser crashing. Replace with this:
while(i<=50)
{
function op(a) {
a -= 0.02;
if(a < 0)
{
a = 1;
}
document.getElementById("slide").style.opacity = a;
}
i++; //increment the counter variable to prevent an infinite loop
}

How to do an animation in Javascript with pause and play options?

function animate(elem,style,from,to,time) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1, (new Date().getTime() - start) / time);
elem.style[style] = (from + step * (to - from))+'px';
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + 'px';
}
Here is my code. and i need to pause and play in it
Finally i found the answer
function animate(elem,style,to,time,callback)
{
if(!elem) return;
_animating = true;
curAnimElem = elem; /*stores the current Element*/
curStyle = style; /*stores the current style*/
curTo = to; /*stores the current to 'px'*/
curCallback = callback; /*stores the current callbak function*/
if(style === 'left'){ from = elem.offsetLeft; }
else if(style === 'top'){ from = elem.offsetTop; }
var start = new Date().getTime(),
animTimer = setInterval(function()
{
if(!pauseV)
{
pauseTime = Math.round(time - (new Date().getTime()-start));
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1 ){ _animating = false; clearInterval(animTimer); if(callback){callback(); callback = null;} }
}
else{clearInterval(animTimer);}
},25);
elem.style[style] = from + 'px';
}
the above code is to animate the elements(left or top only). to PAUSE and PLAY, include the below code in pause/play event function.
function pauseFun()
{
if(pauseV)
{
pauseV = false;
if(_animating){ animate(curAnimElem,curStyle,curTo,pauseTime,curCallback); }
}
else if(!pauseV)
{pauseV = true;}
}
Its works for me......
Thanks.
Use clearInterval(timer) to pause the animation and then timer = setInterval(...) again to resume it. You would need to break the setInterval callback out into its own named function (inside the body of the first function) to make resuming easier.
try this:
var doAnimation=true;
var timer=0;
var start=undefined;
function animate(elem,style,from,to,time)
{
if(!elem && doAnimation) return;
if(start==undefined)start = new Date().getTime();
timer = setInterval(function(){
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1){
doAnimation=false;
clearInterval(timer);
elem.style[style] = from+'px';
start=undefined;
}},25);
}
function fun(){
doAnimation=!doAnimation;
if(doAnimation){play();}
else{pause();}
}
function play(){
animate( document.getElementById('box'),'left',0 , 200, 7000);
}
function pause(){
clearInterval(timer);
}
$(document).ready(function(){
play();
});
Check out the fiddle here:
http://jsfiddle.net/sunnykumar08/V9MHN/1/

Div opacity not working

I have a timer on my div which changes the opacity of the div. But for some reason the maths keeps setting it to 0.1 over and over. And i have no idea why!
This is my code:
function do_it(div){
var opac = parseInt(div.style.opacity);
if(opac == 1){
var dir = 'down';
} else if(opac == 0) {
var dir = 'up';
}
if(dir == 'down'){
opac -= 0.1;
} else {
opac += 0.1;
}
if(opac > 1){
opac = 1;
} else if(opac < 0){
opac = 0;
}
div.style.opacity = opac;
div.timer = setTimeout(function(){ do_it(div) }, 1000);
}
Have provided a fiddle:
JSFiddle
The div opacity should go from 1 to 0 and back up again in steps of 0.1
This is your problem
var opac = parseInt(div.style.opacity);
It should be parseFloat
var opac = parseFloat(div.style.opacity);
function do_it(div,output){
var opac = parseFloat(div.style.opacity);
opac -= 0.1;
if(opac<=0.05){
opac = 1;
}
div.style.opacity = opac;
output.innerHTML = opac;
div.timer = setTimeout(function(){ do_it(div,output) }, 1000);
}
var div = document.getElementById('test');
var output = document.getElementById('op');
do_it(div,output);
parse a number
parseInt(0.9) ==> 0
parseFloat(0.9) ==>0.9
there is no need of extra vars lik up down
http://jsfiddle.net/ckBFy/29/
Even though there's already an accepted answer, I'd like to add that I think that it's still not working the way it was supposed to.
Here's a link to my demo (the way I believe it should have worked).
And here's my corrected version of the code:
way = 'down';
function do_it(div,output){
var opac = parseFloat(div.style.opacity);
if(opac >= 1){
way = 'down';
}
else if(opac <= 0.2) {
way = 'up';
}
if (way === 'down'){
opac -= 0.1;
}
else{
opac += 0.1;
}
div.style.opacity = opac;
output.innerHTML = opac;
div.timer = setTimeout(function(){ do_it(div,output) }, 1000);
}
var div = document.getElementById('test');
var output = document.getElementById('op');
do_it(div,output);

Categories