Animate text change over time with JavaScript - javascript

I need to animate text change over time that never stops.
I've found this simple example with jquery:
$(function() {
$('#header-text-change').fadeOut(500, function() {
$(this).text('Some other text!').fadeIn(500);
});
});
Now I need to have more than one predefined text and that animation loops forever.
Thanks.

You can use setInterval() function to loop every N milliseconds.
Look this code snippet:
This example reset the index variable to 0 when hits TEXTS.length
var TEXTS = ["Some other text!", "Lord of the Rings", "Avengers", "Whatever text"];
var index = 0;
$(function() {
setInterval(function() {
$('#header-text-change').fadeOut(500, function() {
$(this).text(TEXTS[index++]).fadeIn(500);
if (index === TEXTS.length)
index = 0
});
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header-text-change">
Hellow World!!
</h1>
See? now your code is looping, in this case every one second (1000ms).

function fadeout(){$('#header-text-change').fadeOut(undefined,changeText)}
function changeText(){
// implements your logic for changing the text
fadein();
}
function fadein(){$('#header-text-change').fadeIn(undefined,fadeout)}
You call fadeout and it loops using the callbacks( and they are named so you can reference them). Passing undefined as the first argument to fadeOut/fadeIn will use the default value of 400ms, you could change that by passing a variable that stores how long you want the animation to take.

Related

Get child div of existing div using anchors next element without ID or class using JQuery

As you can see below $(nextDiv + ' > div').eq(i).fadeIn('slow'); does not work as it seems to be malformed. nextDiv is on inspection the div below the anchor, how do I achieve getting the two divs that sit inside it?
HTML:
Sub Click
<div>
<div>I want this to fade in on the click</div>
<div>Followed by this etc.</div>
</div>
Javascript:
function subClick(myAnchor)
{
var nextDiv = $(myAnchor).next();
function showDiv(i) {
if (i > 2) return;
setTimeout(function () {
$(nextDiv + ' > div').eq(i).fadeIn('slow');
showDiv(++i);
}, 50);
}
showDiv(0);
}
You are trying to concatenate a string with jQuery, that won't provide a valid selector. The concatenation would provide something like "[object Object] > div" which doesn't select any elements in your code.
Instead, get the div children using children() method on the jQuery nextDiv object.
nextDiv.children('div').eq(i).fadeIn('slow');
If there are only two divs then you can reduce the code using delay() method.
function subClick(myAnchor) {
var nextDivs = $(myAnchor).next().children();
// if you want to do the animation after the first then
// use the below code, where second animation initializing within
// the first animation success callback, which also provides a 50ms
// delay for second animation(avoid .delay(50) if you dont nedd that delay)
// nextDivs.eq(0).fadeIn('slow', function() {
// nextDivs.eq(1).delay(50).fadeIn('slow');
// });
// in case you just want to provide a 50ms delay
// between animation then use, your code does this
nextDivs.eq(0).fadeIn('slow');
nextDivs.eq(1).delay(50).fadeIn('slow');
}
var nextDiv = $(myAnchor).next(); then nextDiv is an object not a selector. If you want to access its div children use this:
nextDiv.children('div').eq(i).fadeIn('slow');

jQuery loop image fadeout/in with time interval

I have a jQuery function to fadeIn/Out images in a div. But when the function reaches last image, it gets stopped. Any way to get it in a loop, so that at the end of last image, it will start again from the first image.
here is the code
HTML:
<div id="homeimg">
<img src="image1.jpg" />
<img src="image2.jpg" />
<img src="image3.jpg" />
<img src="image4.jpg" />
</div>
jQuery:
$(document).ready(function(){
$('#homeimg img:first-child').addClass('activeimg');
setInterval('cycleMe()', 4000);
});
function cycleMe() {
$('.activeimg').next().css('z-index', 10);
$('.activeimg').next().fadeIn(1500);
$('.activeimg').fadeOut(1500, function(){
$(this).next().fadeIn(0);
$(this).next().addClass('activeimg');
$(this).css('z-index', 5).removeClass('activeimg');
});
}
Any possibilities?
First of all, you're passing the function in as a string, which is a no-no. I think you're over-complicating your code, and there are some jQuery efficiencies you can leverage.
First, I don't think it's necessary to modify the z-index of your images: the fading should handle all that. Secondly, you can chain jQuery calls (see below how fadeIn and addClass chained). Lastly, every time you do $('.activeimage'), jQuery has to scan the DOM again, which is inefficient. Best to do it once and cache the answer (whenever I store a jQuery object, I begin it with a dollar sign by convention, so I always know I'm dealing with a jQuery-wrapped object).
Here's how I would re-write this:
$(document).ready(function(){
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
});
function cycleMe() {
var $active = $('#homeimg .activeimg');
var $next = $active.next('img');
if(!$next.length) $next = $('#homeimg img:first-child');
$active.fadeOut(1500, function(){
$(this).removeClass('activeimg');
$next.fadeIn().addClass('activeimg');
});
}
Working jsfiddle: http://jsfiddle.net/6MHDn/
You can also do this with simple array manipulation:
$(document).ready(function () {
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
// get an array of your images
var arrImgs = $('#homeimg img');
function cycleMe() {
var currImg = arrImgs[0];
var nextImg = arrImgs[1];
// You can do this with simple array splicing and pushing
$(nextImg).css('z-index', 10);
$(nextImg).fadeIn(1500);
$(currImg).fadeOut(1500, function () {
$(nextImg).fadeIn(0);
$(this).css('z-index', 5);
// remove the first item from the array
arrImgs.splice(0,1);
// add it to the end of the array
arrImgs.push(currImg);
});
}
});
jsFiddle: http://jsfiddle.net/mori57/4FbVD/
Taking into consideration some of Ethan's comments, I also tried it this way:
http://jsfiddle.net/mori57/4FbVD/2/
$(document).ready(function () {
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
// get an array of your images
var arrImgs = $('#homeimg img');
function cycleMe() {
var currImg = $(arrImgs[0]);
var nextImg = $(arrImgs[1]);
// You can do this with simple array splicing and pushing
nextImg.fadeIn(1500);
currImg.fadeOut(1500, function () {
currImg.removeClass('activeimg');
nextImg.fadeIn(0).addClass('activeimg');
// remove the first item from the array
arrImgs.splice(0,1);
// add it to the end of the array
arrImgs.push(currImg);
});
}
});
In my previous attempt, I was having to requery the DOM both for css change and fadeIn ... inefficient. Cache the jQuery object, /then/ do the manipulation, and sans-z-index as in Ethan's approach. I'd still rather not have to requery the DOM at all for each element inside an infinite loop. If I find a way around that, I'll post it as well.

animation like ning home page in jquery/JS/css?

how to create animation effect like ning home page (http://www.ning.com/) in jquery/JS/css? Iam talking about the curtain like animation for the text "Build and cultivate your own community of followers/fans/members/customers etc". Its a span element with class of "word"
You can create an array of words then loop through the array index with setInterval and use jQuery slideUp - slideDown for the animation.
html:
<p>Build and cultivate your own community of</p>
<div id="word">customers</div>
script:
var words = ['followers', 'fans', 'members', 'customers'];
var index = 0;//start with 0, first array index is 0
var $word = $('#word');
setInterval(function () {
if (index == words.length) {
//if current index is equal to the arrays length reset it to 0
index = 0;
}
//slideUp to hide
$word.slideUp(500, function () {
//on animation complete hidden change the text then slideDown to show
$word.text(words[index]).slideDown(500);
/*
It's always a good practice to separate increment/decrement
in a single line, as it might confuse some(especially new) programmers
*/
index++;
});
}, 2000);
See this jsfiddle.
You can use <span> but it will create a different effect because <span> is an inline element (check this jsfiddle). You need to set it to display:block to achieve the desired effects - jsfiddle demo.
Here's a solution. Made possible through the use of jQuery slideUp() and slideDown(). Additionally to allow for the animation to run every few seconds, I employed standard javascript setInterval().
HTML & JS
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<h1>Build something...</h1>
<h1 id="marqueeText">Testing</h1>
<button id="foo">Foo</button>
<script>
$(document).ready(function() {
// Drumroll, the main function that will start the rolling text.
var drumrollPlease = function() {
var index = 0;
var words = ['Awesome', 'Fun', 'Amazing'];
var marquee = $('#marqueeText');
// Key part here. This is the heart of the script, where your words will get rotated through,
// animating with slideup/slidedown and changing out your words based on the above words array.
window.setInterval(function () {
// Reset to the beginning once we reach end of our words list.
if (index >= words.length) {
index = 0;
}
// Set the marquee container to slide, update the word in our marquee container and then slide back down to reveal
// the new word.
marquee.slideUp('slow', function() {
marquee.html(words[index++]);
marquee.slideDown();
});
}, 2000); // Modify this duration in milliseconds as you please.
}
// I bound my button foo to illustrate how to trigger it. I could
// just as easily have called drumrollPlease() to have the function auto run
// when the document was in the ready state.
$('#foo').click(function() {
drumrollPlease();
});
});
</script>
</body>
</html>
See button activated plunker version: HERE
See automatic activated plunker version: HERE
You can use TweenlitMax
Includes
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.2/TweenMax.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.2/plugins/TextPlugin.min.js"></script>
HTML
<div>Build and cultivate your own community of</div>
<div id="compatibility">Followers</div>
Css:
#compatibility{
width:200px;
font-size:20px;
height:100px;
display:inline-block;
overflow:hidden;
position:absolute;
font-weight:bold;
}
JS:
$(document).ready(function(){
var tl = new TimelineLite({onComplete:onAnimationComplete});
text = $("#compatibility");
tl.fromTo(text,1,{height:0},{height:100})
.fromTo(text,1,{height:100},{height:0})
.set(text,{text:"fans"})
.fromTo(text,1,{height:0},{height:100})
.fromTo(text,1,{height:100},{height:0})
.set(text,{text:"members"})
.fromTo(text,1,{height:0},{height:100})
.fromTo(text,1,{height:100},{height:0});
function onAnimationComplete(){
tl.restart();
}
});
Check Fiddle

jQuery Animation, Chaining, .each() and .animate() (or fadeIn() and fadeOut())

I'm having a bit of a trouble trying to figure this out today, i want to make 5 items inside my DOM (which is listed under the same attribute element, $('.elements')) fade in and out, and after reading up a bit on the API i thought .each() would be a fabulous idea to implement a fade in and fade out showcase gallery.
However, i'm currently using:
$('.elements').each(function() {
$(this).fadeIn(2000).delay(200).fadeOut(2000).show();
})
but everything gets faded in and out at once.
How do i do a sequential effect where everything is chained together and it starts from the first item in the list (a.k.a - $('elements').eq(0)?) down to the last one, and then restarts again?
Do i really need a while loop to do this in javascript/jquery? I was hoping there would be a similar function that i could chain for jQuery to perform to reduce load and filesize.
Also, is there a way to restrict the images from overflowing out from my div?
(function loop() {
$('.elements').each(function() {
var $self = $(this);
$self.parent().queue(function (n) {
$self.fadeIn(2000).delay(200).fadeOut(2000, n);
});
}).parent().promise().done(loop);
}());
demo: http://jsfiddle.net/uWGVN/2/
updated to have it looping without end.
2nd update: a different, probably more readable, approach:
(function fade(idx) {
var $elements = $('.elements');
$elements.eq(idx).fadeIn(2000).delay(200).fadeOut(2000, function () {
fade(idx + 1 < $elements.length ? idx + 1 : 0);
});
}(0));
​demo: http://jsfiddle.net/uWGVN/3/
You can add a callback
offical doc :
('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
and call the same function with i++ et $('.elements').eq(i)
http://jsfiddle.net/dFnNL/
For your overflowing , style it with CSS:
div.(class) { position:relative; overflow:hidden; }
Beautiful way :
(function hideNext(jq){
jq.eq(0).hide("slow", function(){
(jq=jq.slice(1)).length && hideNext(jq);
});
})($('a'))
last first :
(function hideNext(jq){
jq.eq(jq.length-1).hide("slow", function(){
(jq=jq.slice(0,length-1)).length && hideNext(jq);
});
})($('a'))

make div text disappear after 5 seconds using jquery?

i need to make a div text disappear after x seconds of displaying it using an ajax call
can you help me on this please ?
thanks
You can use empty() to remove a <div> contents:
setTimeout(fade_out, 5000);
function fade_out() {
$("#mydiv").fadeOut().empty();
}
assuming:
<div id="mydiv">
...
</div>
You can do this with an anonymous function if you prefer:
setTimeout(function() {
$("#mydiv").fadeOut().empty();
}, 5000);
or even:
var fade_out = function() {
$("#mydiv").fadeOut().empty();
}
setTimeout(fade_out, 5000);
The latter is sometimes preferred because it pollutes the global namespace less.
You can try the .delay()
$(".formSentMsg").delay(3200).fadeOut(300);
call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.
http://api.jquery.com/delay/
$.doTimeout( 5000, function(){
// hide the div
});
You would need to set something like setTimeout('$("#id").fadeOut("slow")', 5000) but other than that it depends on what the rest of your code looks like
This should work:
$(document).ready(function() {
$.doTimeout(5000, function() {
$('#mydiv').fadeOut();
});
});
You may need to display div text again after it has disappeared.
This can be done in 1 line.
$('#div_id').empty().show().html(message).delay(3000).fadeOut(300);
This Answer is without jQuery, you can just grab your element and know its index position.
Then use it in the div below. I will be your div's index number in dom.
const div = document.querySelectorAll('div');
setTimeout(() => {
div[i].textContent = '';
}, 3000);

Categories

Resources