How do I animate dynamic text with JavaScript? - javascript

A span element,
<span id="example">Start</span>
JavaScript
var texts = ["example1", "example2", "example3"];
var count = 0;
function changeText() {
$("#example").text(texts[count]);
count < 3 ? count++ : count = 0;
}
setInterval(changeText, 500);
Fiddle
How can I add animations to the newly added element to span,
I want use animations from animate.css, bounceIn while the element enters and bounceOut while the item disappears and so on till the last item in the list.
Update:
Fiddle updated with animate.css

Try utilizing jQuery UI - Bounce Effect
css
#example {
top:50px;
height:100px;
width:100px;
position:relative;
display:block;
}
js
var texts = ["example1", "example2", "example3"];
var count = 0;
function changeText() {
$("#example").delay(10)
.hide("bounce", {
times: 3
}, 1500, function () {
$(this).text(texts[count]).show("bounce", {
times: 3
}, 1500, function () {
count < 2 ? count++ : count = 0;
changeText();
});
});
}
changeText();
jsfiddle http://jsfiddle.net/989dbjn8/3/

This fiddle should work.
var texts = ["example1", "example2", "example3"];
var count = 0;
function changeText() {
$('#example').addClass('animated infinite bounce');
$("#example").text(texts[count]);
count < 3 ? count++ : count = 0;
}
setInterval(changeText, 500);

Related

Set transition between innerHTML

Need to add fade in and out transition on innerHTML.
I have looked around but didn't find a solution to accomplish this.
I wish to have fade in and out effect between innerHTML texts.
var h2text = ["First h2", "Second H2"];
var counter = 0;
var h2 = document.getElementById("changeH2");
var inst = setInterval(change, 2000);
function change() {
h2.innerHTML = h2text[counter];
counter++;
if (counter >= h2text.length) {
counter = 0;
}
}
<h2 id="changeH2"></h2>
You can utilise CSS classes and transitions to do this by fading the element in and out when the text changes. I've also included another timeout.
var h2text = ["First h2", "Second H2"];
var counter = 0;
var h2 = document.getElementById("changeH2");
var inst = setInterval(change, 2000);
function change() {
h2.classList.add('fade');
setTimeout(function(){
h2.innerHTML = h2text[counter];
h2.classList.remove('fade');
counter++;
if (counter >= h2text.length) {
counter = 0;
}
}, 500);
}
h2{
transition: opacity .5s ease;
}
.fade{
opacity: 0;
}
<h2 id="changeH2"></h2>
Improved a little your js (using modulo instead of your three-line-condition), and created a small animation that seems to fit your requirements.
let h2text = ["First h2", "Second H2"];
let counter = 0;
let h2 = document.getElementById("changeH2");
let inst = setInterval(change, 2000);
function change() {
h2.innerHTML = h2text[counter];
counter = (counter + 1) % h2text.length;
}
#changeH2{
opacity: 0;
animation: fade infinite 2s;
}
#keyframes fade{
20%{
opacity: 1;
}
80%{
opacity: 1;
}
}
<h2 id="changeH2"></h2>
You could achieve this bij using the opacity like this
var h2text = ["First h2", "Second H2"];
var h2 = document.getElementById("changeH2");
h2.style.transition = "0.5s"; //fade speed
setTimeout(function () {
h2.style.opacity = 0; //make text temporarily invisible
setTimeout(function() {
h2.innerHTML = h2text[1];
h2.style.opacity = 1; //fade back in
}, 500); //this timeout needs to be the same as the transition speed
})
<h2 id="changeH2">First h2<h2/>
Here you don't have to do anything with your css.
Simple plugin for text transition.
(function($) {
let KeyWord = ["First h2", "Second H2"];
let counter = 0;
let Flag = true;
function rotaterator() {
setTimeout(function() {
if (counter == 2) {
counter = 0;
}
if (Flag) {
Flag = false;
counter = 1;
}
$("#changeH2").fadeOut(function() {
$("#changeH2").text(KeyWord[counter]);
counter++;
}).fadeIn(function() {});
rotaterator();
}, 2000);
}
rotaterator();
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="changeH2"></h2>

How to set up "stop" after setInterval() method?

i have image gallery ant i set up setinterval, now i want that it should be stopped after two or tree circle.
This is my html Code:
<div id="slider">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/24/formats/24_web.jpg">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/27/formats/27_web.jpg">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/32/formats/32_web.jpg">
<img src="http://imgsrc.hubblesite.org/hu/gallery/db/spacecraft/33/formats/33_web.jpg">
</div>
css:
#slider {
width: 400px;
height: 300px;
position: relative;
overflow: hidden
}
#slider img {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: 0.25s
}
and Javascript:
var pics;
var current = 0; // first next() moves to pics[0], the first image
window.addEventListener("load", function() {
pics = document.querySelectorAll("#slider img");
});
setInterval(function() {
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
}, 3000);
Here's your answer: Stop setInterval call in JavaScript
Save the interval ID when you create it, keep track of the number of times your slides have rotated, and then cancel the interval.
Use a counter variable to track the number of cycles & clear the timer based on that limit value.
JS Code:
var counter = 0;
var limit = 3 ;
var timer;
timer =setInterval(function () {
if(counter === 3){
clearInterval(timer);
return;
}
counter++;
//do some stuff here after 1 second delay
},1000);
You could use setTimeout instead.
var pics;
var current = 0; // first next() moves to pics[0], the first image
var stop = 3; //define when you want to stop
window.addEventListener("load", function() {
pics = document.querySelectorAll("#slider img");
});
function switchImage()
{
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
stop--;
if(stop != 0)
setTimeout(switchImage,3000);
}
setTimeout(switchImage,3000);
You can do like this.
var refreshIntervalId = setInterval(function() {
var nextImage = (current + 1) % pics.length;
pics[current].style.opacity = 0;
pics[nextImage].style.opacity = 1;
current = nextImage;
}, 3000);
clearInterval(refreshIntervalId);

Stop loop and fade in area that is hovered on

I have a bit of javascript/jquery I am trying to figure out. What I have already is three boxes that the content fades in and out and loops through the three and repeats. What I am trying to do is when "box x" is hovered over the loop fades out and stops never to start again, and the box that is hovered on, the content below the box fades in and stays... unless another box is hovered over, then the content that faded in from the other hovered box will fade out and the new box that was hovered on, the content that coincides with that box fades in and stays fade in, and so forth.
How would I go about doing this?
Here is a jsfiddle example: http://jsfiddle.net/q0htx0no/
javascript/jquery
var infoboxes = $(".count p");
var counter = 0;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000);
});
}
$(function() {
rotate();
});
Thanks for any help
One option would be to have a global variable (a 'flag') that would indicate if the rotation should be stopped. Once a box has been hovered over, it should set hovered to True and should fade in that specific box.
Yep, use a global variable. Something like this:
var infoboxes = $(".count p");
var counter = 0;
var goAhead = true;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
checkRotate();
})
}, 1000);
});
}
function checkRotate() {
if (goAhead) { rotate(); }
}
$('.about').on('mouseover', function() {
goAhead = false;
var index = $(this).index();
var boxesToClear = $(infoboxes).filter(function(i) { return i !== index; });
$(boxesToClear).fadeOut(1000, function() {
$(infoboxes[index]).fadeIn(1000);
});
});
checkRotate();
DEMO
Here's one way to do it. It can probably be improved.
http://jsfiddle.net/vbt67x0h/2/
var infoboxes = $(".count p");
var counter = 0;
var isrotating = false;
function rotate(){
isrotating = true;
$(infoboxes[counter]).fadeIn(1000).delay(1000).fadeOut(1000);
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
}
//immediately stop rotate and hide all
function stoprotate(){
clearInterval(tmrrotate);
isrotating = false;
for(var x=0;x<infoboxes.length;x++){
$(infoboxes[x]).stop();
$(infoboxes[x]).hide();
}
}
rotate();
//rotate every 3 seconds, 1 to fadein, 1 to pause, 1 to fadeout
var tmrrotate = setInterval(function() {
rotate();
}, 3000);
$(".about").on('mouseover', function() {
if(isrotating){stoprotate()}
$(infoboxes[$(this).index()]).fadeIn(1000);
})
.on('mouseleave', function() {
$(infoboxes[$(this).index()]).fadeOut(1000);
});
You should make a timed array:
var arTimer = [];
and push all timers into that array, clearTimeout on hover and show only hovered index:
var infoboxes = $(".count p");
var counter = 0;
var arTimer = [];
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
arTimer.push(setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000));
});
}
function cleararTimer(){
for (var i = 0; i < arTimer.length; i++) {
clearTimeout(arTimer[i]);
}
}
$(function() {
rotate();
$('.about').on('mouseover', function(){
cleararTimer();
var hovered = $(this).index();
$('.count p').not(':eq('+hovered+')').fadeOut(1000);
$('.count p:eq('+hovered+')').fadeIn(1000);
});
});
jsFiddle Example

Adding delay to DIV animation

I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/54hqm/3/
Now I want to happen after each click, is basically to move each DIV one after another, with a delay, instead of moving the whole stack of DIVs at once. I don't exactly know what to do. Can anyone help me with that?
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
You can make this with 2 small modifications:
In your each() function, add the index parameter to know the index of the currently animating packet:
$(".t").each(function (index) {
Before your animate calls, insert a packet.delay() with a delay increasing with every item:
packet.delay(index * 250);
I updated your fiddle to show results.
Update: I made a second version based on your comment.

JS Image Transition Not Working

I am unable to get the CSS opacity transition to work by adding it using JavaScript. Please let me know what is wrong with the code. http://jsfiddle.net/copperspeed/bvWbB
(function () {
var myImgs = document.getElementById('vz0');
var i = 0;
function cycle() {
if (i <= 3) {
var myArray = [
'http://jsrun.it/assets/t/r/U/O/trUOT.jpg',
'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg',
'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg',
'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'
];
console.log(myArray[0]);
myImgs.setAttribute("src", myArray[i]);
if (myImgs.style.opacity === '0') {
console.log('trans');
myImgs.style.transitionProperty = 'opacity';
myImgs.style.transitionDuration = "1500ms";
}
if (myImgs.style.opacity === '1') {
console.log('opacity-0');
myImgs.style.opacity = '0';
}
i++;
setTimeout(function () {
cycle();
}, 3000);
There are a couple of issues with your script.
the opacity style doesn't exist on the element on initialization. You need to account for that in your logic
On the second pass through, the opacity style does exist and may be 0, so that condition also needs to be accounted for
Your second if statement immediately reverses what you did in the first conditional. That statement should be in an else-if
You are cycling only one image element in/out so your transition from one image to another won't work as expected. You either need to change to two elements or change your transitioning strategy to accommodate the single element.
Demo fiddle - items 1-3 above
Code changed for 1-3 above:
(function () {
var myImgs = document.getElementById('vz0');
var i = 0;
function cycle() {
if (i <= 3) {
var myArray = ['http://jsrun.it/assets/t/r/U/O/trUOT.jpg', 'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg', 'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg', 'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'];
myImgs.setAttribute("src", myArray[i]);
if (myImgs.style.opacity === '' || myImgs.style.opacity == 0) {
console.log(myImgs.style.opacity + '0');
myImgs.style.transitionProperty = 'opacity';
myImgs.style.transitionDuration = "1500ms";
myImgs.style.opacity = 1;
} else if (myImgs.style.opacity == 1) {
console.log(myImgs.style.opacity + '2');
myImgs.style.opacity = 0;
}
i++;
setTimeout(function () {
cycle();
}, 3000);
if (i === 4) {
i = 0;
}
}
}
cycle();
}());
For item #4 above - here is a refactored version that uses two img elements to help manage the transition in and out:
Demo fiddle for 1-4 above
HTML:
<div class="imgWrapper">
<img src="http://jsrun.it/assets/t/r/U/O/trUOT.jpg" id="vz0" class="vzImage" alt="first" height="300" width="300" />
<img src="http://jsrun.it/assets/t/r/U/O/trUOT.jpg" id="vz1" class="vzImage" alt="first" height="300" width="300" />
</div>
CSS:
.imgWrapper {
position: relative;
height: 300px;
width: 300px;
}
.vzImage {
opacity:0;
position: absolute;
top: 0; left: 0;
bottom: 0; right: 0;
}
Script:
(function () {
var myImgs = document.getElementsByClassName('vzImage');
var myArray = ['http://jsrun.it/assets/t/r/U/O/trUOT.jpg',
'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg',
'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg',
'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'];
// Consider moving this to .vsImage in stylesheet
for(var j = 0; j < myImgs.length; ++j) {
myImgs[j].style.transitionProperty = 'opacity';
myImgs[j].style.transitionDuration = "1500ms";
}
function cycle(i) {
var myArrayIdx = i % myArray.length;
var imgIdx = i % myImgs.length;
var prevImgIdx = (i-1) % myImgs.length;
myImgs[imgIdx].setAttribute("src", myArray[myArrayIdx]);
myImgs[imgIdx].style.opacity = 1;
if(myImgs[prevImgIdx]) {
myImgs[prevImgIdx].style.opacity = 0;
}
setTimeout(function () {
cycle(i+1);
}, 3000);
}
cycle(0);
}());
First rule of debugging. If something inside IF statement doesn't happen, look at the condition.
You check if myImgs.style.opacity equals 0 or 1. Use console.log(myImgs.style.opacity); and it'll show you that myImgs.style.opacity equals empty string. So none of your conditions ever fire.

Categories