Text carousel on timer with fade in, fade out - javascript

I'm trying to have some text fade out, change, and fade back in at regular intervals and automatically (ie, no button).
I cannot get this code to synchronize setInterval with the fading. I've tried fadeToggle as well as a combination of fadeIn and fadeOut together.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="changeText">Zero</div>
<script type="text/javascript">
var text = ["One", "Two", "Three"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 3000);
function change() {
$("#changeText").fadeToggle(3000);
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
</script>
PS I am agnostic about the solution. If this can be done more elegantly in CSS (which I've used for fading but not transition), please let me know.

Try utilizing .fadeTo() , remainder operator
var text = ["One", "Two", "Three"];
var counter = 0;
var elem = document.getElementById("changeText");
function change() {
$(elem).fadeTo(3000, 0, function() {
this.innerHTML = text[counter];
counter = ++counter % text.length;
$(this).fadeTo(3000, 1, change)
})
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="changeText">Zero</div>
<script type="text/javascript">
</script>

There are a million ways to skin a cat. If you want to do fadeToggle, I wouldn't also use setInterval, because they will be called at the same time and cancel each other out.
One thing to keep in mind is that fadeToggle will effect more than just the opacity and turns the objects display off once it is hidden, and that could effect your layout.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="changeText">Zero</div>
<script type="text/javascript">
var text = ["One", "Two", "Three"];
var counter = 0;
var elem = document.getElementById("changeText");
$(document).ready(function(){ change()});
function change() {
$("#changeText").fadeToggle(3000, 'swing', function(){
if($("#changeText").css("display") == "none")
{
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
change();
});
}
</script>

I'm not sure how this compares performance wise. This implementation has no dependencies.
(function() {
var STEP = 0.1;
var x = 0;
var text = ['one', 'two', 'three'];
var element = document.querySelector('#changeText');
if(!element) { return; }
element.innerText = text[0];
requestAnimationFrame(change);
function change() {
var y = Math.sin( x );
var opacity = (y + 1) / 2;
x += STEP;
element.style.opacity = opacity;
if(y <= -0.99 && Math.sin(x) > -0.99) {
var txtIdx = text.indexOf(element.innerText);
if(txtIdx === text.length - 1) {
element.innerText = text[0];
} else {
element.innerText = text[++txtIdx];
}
}
requestAnimationFrame(change);
}
})()

Related

I want my text change animation in javascript to have smooth transition

So I have an h1 ("Hello, I'm xxxxxxxxx") and wraped "Hello" in span with "greeting" id and I change the text in js every 3s to an Hello in another language. It works fine but I want it change smoothly but not pop up suddenly.
// change text every 3 second
var text = ["Hola", "Hallo", "Merhaba"];
var counter = 0;
var elem = document.getElementById("greeting");
setInterval(change, 3000);
function change() {
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
With Jquery, you might want to use fadeOut(), then fadeIn() functions.
And your code would be like:
var text = ["Hola", "Hallo", "Merhaba"];
var counter = 0;
var elem = $("#greeting");
setInterval(change, 3000);
function change() {
elem.fadeOut(function(){
elem.html(text[counter]);
counter++;
if(counter >= text.length) { counter = 0; }
elem.fadeIn();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='greeting'>Hello<div>
You could do it just by adding some css and using the transition property.
var greet = new Array("Hola", "Hallo", "Merhaba");
var counter= 0;
document.getElementById('greeting').innerHTML = greet[counter];
Changegreeting1();
function Changegreeting1(){
incrementIndex()
document.getElementById('greeting1').innerHTML = greet[counter];
document.getElementById('greeting').style.opacity = 0;
document.getElementById('greeting1').style.opacity = 1;
setTimeout(Changegreeting, 2000);
}
function Changegreeting(){
incrementIndex();
document.getElementById('greeting').innerHTML = greet[counter];
document.getElementById('greeting').style.opacity = 1;
document.getElementById('greeting1').style.opacity = 0;
setTimeout(Changegreeting1, 2000);
}
function incrementIndex(){
if(counter < greet.length - 1 ){
counter++;
}else{
counter = 0;
}
}
#greeting{
transition: opacity 1s;
}
#greeting1{
transition: opacity 1s;
position:absolute;
top:0px;
margin-top:0px
}
<p id = "greeting"></p>
<p id = "greeting1"></p>
Is that what you want
If by "change smoothly" you mean some smooth transition, as in fade out and fade in, I would suggest looking at jQuery fadeOut and fadeIn methods.
The change() function with animation duration set to 100 could look something like this:
function change() {
// Fade out
$("#greeting").fadeOut(100, function() {
// Increment the counter
counter++;
if(counter >= text.length) { counter = 0; }
// Update the text and fade in
$("#greeting").text(text[counter]).fadeIn(100);
})
}

How to return original inner text on mouseleave?

I would like to randomize characters on hover for a specific id.
It works fine on mouse enter but can't get it stop and back to initial text when mouse leave.
Here's the code.
jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var $_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
$("#text-shuffle").mouseenter(text_shuffle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
Thanks for your help
Use clearInterval to stop the randomize characters, replace the original text when mouse goes out of text.
jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
var value, $_inter;
$("#text-shuffle").mouseenter( function(){
value = $(this).html();
text_shuffle();
}).
mouseout(function(){
clearInterval($_inter);
$(this).html(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
You need to clear your interval on mouseleave. You haven't called a mouseleave function so your code scrambles the chars inside your div indefinitely.
All I've done was set the interval to a variable and clear the variable on mouseleave.
jQuery(function($) {
all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var int;
var counter = 0;
function textShuffle() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}
$("#text-shuffle").hover(function() {
int = setInterval(textShuffle, 100);
}, function () {
clearInterval(int);
document.getElementById("text-shuffle").innerText = "Home";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
(function(){
'use strict';
var all = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
elem = document.getElementById("text-shuffle"),
orig = elem.innerHTML;
var $_inter;
function text_shuffle()
{
var counter = 0;
$_inter = setInterval( function()
{
elem.innerHTML = elem.innerHTML.substring(0, counter) + all.charAt(( Math.random() * all.length ) | 0 ) + elem.innerHTML.substring(counter + 1);
counter = (counter+1) % elem.innerHTML.length;
}, 100);
}
function clear() { clearInterval( $_inter ); elem.innerHTML = orig };
$("#text-shuffle").hover( text_shuffle, clear )
}())

How to add a fade in and fade out effect to existing js code

Basically I have this code that hooks onto a certain element in the website and overrides it's content. In this example it's overriding existing text to make it change every so often. However when it cycles through the preset text lines it simply jumps without an animation. Is it possible to add a fade animation between the preset texts?
Here is the code:
var text = ["Question Everything!", "Envision the future!", "Change your perspective!"];
var counter = 0;
var elem = document.getElementById("slogantxt");
setInterval(change, 3500);
function change() {
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
CSS3 #keyframes animations would be much lighter weight here.
#keyframes fadeOutIn {
0% {opacity: 1;}
50% {opacity: 0;}
100% {opacity: 1;}
}
.fadeOutIn {
animation-name: fadeOutIn;
animation-duration: 200ms;
}
And then simply remove and re-add the class when changing the inner HTML.
EDIT: for simplicity, I left out the necessary -webkit- prefixes. Don't forget!
With JS you can do like below
var text = ["Question Everything!", "Envision the future!", "Change your perspective!"];
var counter = 0;
var elem = document.getElementById("slogantxt");
setInterval(change, 3500);
function change() {
fade(elem,function(){
elem.innerHTML = text[counter];
unfade(elem);
});
counter++;
if(counter >= text.length) { counter = 0; }
}
function fade(element,cbk) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
cbk();
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
function unfade(element) {
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
Ref: How to do fade-in and fade-out with JavaScript and CSS
With jQuery you could do something like this:
$(document).ready(function(){
var text = ["Question Everything!", "Envision the future!", "Change your perspective!"];
var counter = 0;
setInterval(change, 3500);
function change() {
$("#slogantxt").fadeOut('fast',function(){//fade out the element
$(this).html(text[counter]).fadeIn('fast');//once fade out completes, change the element text and fade it back in
});
counter++;
if(counter >= text.length) { counter = 0; }
}
});

Hide element with a delay

In this case the element hides at ones. Can't understand why it's not show a "P" tag at first and then slowly hides it. Please, help me to fix a problem.
var step = 0.1;
var delay = 90000;
var displayMe = function() {
if (element.style.opacity < 1) {
element.style.opacity += step;
setTimeout('displayMe()', delay);
}
}
var hideMe = function() {
var elem = document.getElementById('regform');
if (elem.style.opacity >= 0) {
elem.style.opacity -= step;
setTimeout('hideMe ()', delay);
}
}
hideMe();
<p id="regform">aaaaaaaaaaaaaaaaa</p>
Element.style.prop will read only inline styles. Define style='opacity:1' for <p> element.
var step = 0.1;
var delay = 1000;
var displayMe = function() {
if (element.style.opacity < 1) {
element.style.opacity += step;
setTimeout(displayMe, delay);
}
}
var hideMe = function() {
var elem = document.getElementById('regform');
if (elem.style.opacity >= 0) {
elem.style.opacity -= step;
setTimeout(hideMe, delay);
}
}
hideMe();
<p id="regform" style='opacity:1'>aaaaaaaaaaaaaaaaa</p>
Try
document.getElementById('regform').style.opacity=1;
var hideMe = function()
{
var elem = document.getElementById('regform');
if(elem.style.opacity>0)
{
elem.style.opacity-= step;
setTimeout(hideMe, delay);
}
}
hideMe();
Fiddle
Try it with jquery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#regform').delay(1000).fadeOut(2000);
});
</script>
<p id="regform" style='opacity:1'>aaaaaaaaaaaaaaaaa</p>
Documentation .fadeOut()

Jquery - Animate innerHTML possible?

I'm trying to have a function that does setTimeout, then changes the innerHTML:
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function(){
document.getElementById("middlecolor").innerHTML='new text new text';
}, 1000);
});
</script>
Question: How could I animate the new text that appears, i.e. line by line as opposed to being written all at once?
Thanks for any suggestions!!
Try something like this:
<div id="text">
</div>
$(document).ready(function () {
var interval = setInterval(function () {
$('#text').append('<p style="display: none;">new text</p>');
$('#text p:last').fadeIn('slow');
}, 5000);
});
See the example here
If you want to kill the interval, can be doing this:
clearInterval(interval);
Greatings.
Line-by-line is a bit tricky, but possible.
var ps = document.getElementById("text").children;
var i = 0;
var $p = $(ps[i]);
setTimeout(function newline(){
$p.css("height", function(index, h){
h = parseInt(h);
h += parseInt($p.css("line-height"));
console.log(h, ps[i].scrollHeight);
if (h > ps[i].scrollHeight)
$p = $(ps[++i]);
return h;
});
if (i < ps.length)
setTimeout(newline, 200);
}, 200);​
I'd suggest to use a typewriter effect, which is also very likable: http://jsfiddle.net/pZb8W/1/
var ps = document.getElementById("text").children;
var i = 0;
var $p, text;
var speed = 20;
setTimeout(function newchar(){
if (!text) {
$p = $(ps[i++]);
text = $p.text();
$p.empty().show();
}
$p.append(document.createTextNode(text.charAt(0)));
text = text.slice(1);
if (text.length || i < ps.length)
setTimeout(newchar, Math.random()*speed+speed);
}, 3*speed);​
Here's a function that would animate in multiple lines of text, one after the other:
<script type="text/javascript">
$(document).ready(function(){
function animateAddText(id, text, delta) {
var lines = text.split("\n");
var lineCntr = 0;
var target = $("#" + id);
function addLine() {
if (lineCntr < lines.length) {
var nextLine = "";
if (lineCntr != 0) {
nextLine = "<br>";
}
nextLine += lines[lineCntr++];
$("<span>" + nextLine + "</span>").hide().appendTo(target).fadeIn(1000);
setTimeout(addLine, delta);
}
}
addLine();
}
var multilineText = "First line\nSecond Line\nThird Line\nFourth Line\nFifth Line";
animateAddText("middlecolor", multilineText, 1000);
});
</script>
And a working demo: http://jsfiddle.net/jfriend00/Gcg5T/

Categories

Resources