How do I add fade in fade out to inner HTML? - javascript

How can I get the fade in and fade out when the array item changes in inner HTML ? I would like it to fade out and disappear and then the next language to fade in to appear.
var langs = ["Tamil", "Hindi", "Kannada", "Malayalam"];
var count = 0;
var langLength = langs.length;
var language = document.querySelector(".language");
setInterval(e => {
count = count % langs.length;
var newColour = langs[count];
language.innerHTML = `${newColour}`
count = count + 1;
}, 1500);
.language {
font-weight: bold;
}
<div class="content">
This language <span class="language"></span> <br>
is an Indian language.
</div>

You can use an infinite animation in CSS. Set the duration of the animation equal to the value used for setinterval.
var langs = ["Tamil", "Hindi", "Kannada", "Malayalam"];
var count = 0;
var langLength = langs.length;
var language = document.querySelector(".language");
setInterval(e => {
count = count % langs.length;
var newColour = langs[count];
language.innerHTML = `${newColour}`
count = count + 1;
}, 1500);
.language {
font-weight: bold;
animation: fadeOutIn 1.5s infinite;
}
#keyframes fadeOutIn {
0%,
100% {
opacity: 0
}
50% {
opacity: 1
}
}
<div class="content">
This language <span class="language"></span> <br> is an Indian language.
</div>

Related

JS animation Loop Transitions

var i = 1;
const title = document.getElementById("display-heading");
var texts = [
"Karibu",
"Bienvenido",
"স্বাগতম।",
"Willkommen",
"أهلا بك",
"Bienvenue"
];
title.textContent = texts[0];
var loop = setInterval(function() {
title.textContent = texts[i];
i = (i+1) % texts.length; // Allows the array to loop
}, 1000);
How would I add a fade in/slow down the transition?
https://codepen.io/elliebrayton/pen/vYJBOBP
There is a little discrepancy between the CSS and the HTML: the HTML has an id attribute with name "display-heading", while the CSS defines attributes for a class with that name.
You can get the fading going by changing the opacity.
Here is a runnable snippet:
const title = document.getElementById("display-heading");
var texts = [
"Karibu",
"Bienvenido",
"স্বাগতম।",
"Willkommen",
"أهلا بك",
"Bienvenue"
];
title.addEventListener("transitionend", loop);
function loop() {
if (title.style.opacity != "1") {
texts.push(title.textContent = texts.shift());
title.style.opacity = 1;
} else {
setTimeout(() => title.style.opacity = 0, 500);
}
}
setTimeout(loop);
#display-heading{
font-size: 30px;
transition: 0.5s opacity;
opacity: 0;
}
<h1 id='display-heading'>Welcome</h1>

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 repeat randomised img endlessly on javascript?

I have a function that render random image without repeating, but it stops working when the array of images has come to an end, my goal is to restart function with another random order of images, so function can work infinite. I've read another questions, but didn't find something appropriate to me case.
Here is html part:
<div class="card">
<div class="front" onClick="pickimg();return false;"><img
src="1.jpg" alt=""></div>
<div class="back"><img src="2.jpg" name="randimg"></div>
</div>
Css (just in case):
.card {
width: 200px;
height: 300px;
position: relative;
perspective: 1000px;
cursor: pointer;
margin: 0 50px;
}
.front, .back {
width: 100%;
height: 100%;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: 1s;
backface-visibility: hidden;
border-radius: 10px;
}
.front {
transform: rotateY(360deg);
}
.back {
transform: rotateY(180deg);
}
And JS:
var cards = document.querySelectorAll('.card')
Array.from(cards).forEach(function(card) {
card.addEventListener('click', function() {
Array.from(card.querySelectorAll('.back, .front')).forEach(function(el) {
['back', 'front'].forEach(function(s) {
el.classList.toggle(s)
});
});
});
});
var usedImages = {};
var usedImagesCount = 0;
function pickimg(){
var imagenumber = 3;
var randomnumber = Math.random();
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array();
images[0] = "";
images[1] = "3.jpg";
images[2] = "4.jpg";
images[3] = "2.jpg";
var image = images[rand1];
if (!usedImages[rand1]){
document.randimg.src = images[rand1];
usedImages[rand1] = true;
usedImagesCount++;
if (usedImagesCount === images.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
pickimg();
}
}
Thank you for your help.
You could try something like this:
let img = [1,2,3,4,5];
function switchImage () {
for(; ; ){
let x = Math.random() * 10;
if(typeof img[Math.round(x)] !== 'undefined') {
img.splice(x, 1);
break;
}
}
console.log(img);
if (img.length > 0){
setTimeout(() => switchImage (),1000);
}
}
switchImage();
This is a simplified example where every second the function calls itself again and a new image is picked from the image array. The old image is cut out of the array and the function will stop calling itself when every picture is shown.
Try this -
int lastIndex = Math.round(Math.random()*(imagenumber - 1)) + 1;
function pickImg(){
let imagenumber = 3;
int currIndex = Math.round(Math.random()*(imagenumber - 1)) + 1;
images = new Array();
images[0] = "2.jpg";
images[1] = "3.jpg";
images[2] = "4.jpg";
if (lastIndex !== currIndex) {
document.randimg.src = images[currIndex];
lastIndex = currIndex;
}
else {
pickImg();
}
}
If you didn't get any image displayed that means you have to deal with when images[index] returns undefined.
Inshort you need to have index in images always equal to some value.
How about simple like this does this work for you? at least it will not give you same number a row
var imgArr = [1, 2, 3, 4, 5, 6] // imagine this is your img
var lastImgIndex;
function loadImg() {
var RandomIndex = Math.floor((Math.random() * imgArr.length) + 1);
if (lastImgIndex != RandomIndex) {
$('span').text(RandomIndex + ' index of img show');
lastImgIndex = RandomIndex;
} else {
loadImg();
}
}
loadImg();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>

How to make casino-like increment of a letter?

I need to convert (when the user does something):
adcb
to (the next letter of every letter):
bedc
Currently I am just going with javascript and overwrite the character.
Remember the Pkmn Game Corner?
Wouldn't it be cool if we could simulate that movement of the character (in the pic, change from 7 to Pikachu)?
PS - I have no idea on how to approach this...
This can be achieved with CSS animations to move the letter around, updating the letter when it is not visible.
jsfiddle
HTML:
<div id="reels">
<div>A</div>
<div>L</div>
<div>E</div>
<div>X</div>
</div>
<button id="slide">Slide</button>
CSS:
#reels > div {
width: 20px;
height:30px;
overflow:hidden;
padding:3px;
display:inline-block;
}
#reels > div.reel-change {
animation: slideReel 1s 1;
}
#keyframes slideReel {
0% {
transform: translateY(0);
}
49% {
transform: translateY(-30px);
}
50% {
transform: translateY(30px);
}
100 % {
transform: translateY(0px);
}
}
#reels {
margin-bottom:10px;
}
JavaScript:
$(function() {
$('#slide').click(function() {
var delay = 0;
$('#reels').children().each(function() {
var reel = this;
setTimeout(function() {
$(reel).toggleClass("reel-change");
}, delay);
setTimeout(function() {
changeLetter(reel);
}, delay + 500);
setTimeout(function() {
$(reel).toggleClass("reel-change");
}, delay + 1000);
delay += 500;
});
});
});
function changeLetter(el) {
el.innerHTML = incrementChar(el.innerHTML);
}
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c);
return alphabet[index + 1] || alphabet[0];
}
Edit: Seeing as it's a good reason for doing it based on your above comments, I made it a bit prettier!!
https://jsfiddle.net/bigalreturns/ctuujz3j/2/
For the record, this is what you can do...
var strMsg = 'abcdef';
var tmpStr = '';
function nextLetter(letter) {
var charCode = letter.charCodeAt(0);
return String.fromCharCode((charCode - 96) % 26 + 97)
}
for(var i=0; i < strMsg.length; i++) {
tmpStr += nextLetter(strMsg[i]);
}
console.log(tmpStr); // bcdefg

Punctuation loading "animation", javascript?

I'm looking for a good way to display some punctuation loading "animation".
What I want is something like this:
This will display at second 1: "Waiting for your input."
This will display at second 2: "Waiting for your input.."
This will display at second 3: "Waiting for your input..."
This will display at second 4: "Waiting for your input...."
This will display at second 5: "Waiting for your input."
This will display at second 6: "Waiting for your input.."
This will display at second 7: "Waiting for your input..."
This will display at second 8: "Waiting for your input...."
And so on.
I started by surrounding the dots in spans and thought I could loop through them with jquery and display one more, one more, one more, then reset to 1. But the code got very clumsy, so I wonder how you would do this?
Pure CSS solution
Demo: jsfiddle.net/feklee/D59P9
HTML:
Waiting<span class="dots"><span>.</span><span>.</span><span>.</span></span> for more.
CSS:
#keyframes dots-1 { from { opacity: 0; } 25% { opacity: 1; } }
#keyframes dots-2 { from { opacity: 0; } 50% { opacity: 1; } }
#keyframes dots-3 { from { opacity: 0; } 75% { opacity: 1; } }
#-webkit-keyframes dots-1 { from { opacity: 0; } 25% { opacity: 1; } }
#-webkit-keyframes dots-2 { from { opacity: 0; } 50% { opacity: 1; } }
#-webkit-keyframes dots-3 { from { opacity: 0; } 75% { opacity: 1; } }
.dots span {
animation: dots-1 1s infinite steps(1);
-webkit-animation: dots-1 1s infinite steps(1);
}
.dots span:first-child + span {
animation-name: dots-2;
-webkit-animation-name: dots-2;
}
.dots span:first-child + span + span {
animation-name: dots-3;
-webkit-animation-name: dots-3;
}
WebKit-only alternative
Advantage: No nested tags. This means that the ellipsis could be put as content
into an ::after pseudo element.
Demo: jsfiddle.net/feklee/vFT7W
HTML:
Waiting<span>...</span> for more.
CSS:
body {
font-family: 'Roboto', sans-serif;
font-size: 50px;
}
#-webkit-keyframes dots {
0% { background-position: 0px; }
100% { background-position: 50px; }
}
span {
background: linear-gradient(to right, white 50%, black 50%);
color: transparent;
-webkit-background-clip: text;
-webkit-animation: dots 1s infinite steps(4);
padding-right: 40px;
margin-right: -40px;
}
The trick to making a string of dots is to make a sparse Array and then join all the elements with the desired character.
var count = 0;
setInterval(function(){
count++;
var dots = new Array(count % 10).join('.');
document.getElementById('loadingtext').innerHTML = "Waiting for your input." + dots;
}, 1000);
Here is a Live demo.
This can be very easy:
HTML
<span class="dots"></span>
JQuery
setInterval(function() {
var th = $('.dots');
if(th.text().length < 5){
th.text(th.text()+".");
}else{
th.text("");
}
}, 500);
Demo
Now sure how the code got out of hand, you could just do:
setInterval(function () {
var span = $("#text-loader").children("span:eq(0)");
var ellipsis = span.html();
ellipsis = ellipsis + ".";
if (ellipsis.length > 5) {
ellipsis = ".";
}
span.html(ellipsis);
}, 1000);
<div id="text-loader">
This will display at second 1: "Waiting for your input<span>.</span>
</div>
And as for the 1, you can swap that out with the number of periods.
try this function: i'v put an example here http://jsfiddle.net/XFd39/
var i=0;
function f() {
if(i<=4)
$('#a').append(".");
i++;
if(i==4){
$('#a').html("");
i=0;
}
setTimeout(f,500);
}
f();
Here is a pretty simple variant: http://jsfiddle.net/psycketom/FusdC/
Read the comments below to understand what everything is doing there.
var span = $('.dots'); // take the element where you have the maximum count of dots
var text = span.text(); // cahce it's text value
// we set up a function here, so we can loop it all the time
var loading = function()
{
$({
count : 1 // we start at one dot
}).animate({
count : text.length // together forming all of it
}, {
duration : 1000, // make the animation complete in one second
step : function() {
span.text( text.substring(0, Math.round(this.count)) ); // on each step, change the text accordingly to current iteration
},
complete : function() {
loading(); // once complete, start all over again
}
});
};
loading(); // start it up for the first time
Here you also gain the advantage of using easing if you wish, easily changing total duration and bunch of other benefits in case you're good with jQuery.
Dude, unless you want to display this animation forever you will need a way to stop the animation, or?
Don't even think about global variables, this is JavaScript and it's got closures for that :)
<p>please wait<span id="wait"></span></p>
<input type="submit" id="start" value="start">
<input type="submit" id="stop" value="stop">
<script type="text/javascript">
$(document).ready(function() {
var animator = function($el) {
var dotCount = 1;
var started = true;
return {
"start" : function step() {
dotCount = (dotCount + 1) % 10;
$el.text(new Array(dotCount).join('.'));
if (started) {
setTimeout(step, 100);
}
},
"stop" : function() {
started = false;
}
}
};
var animatedWait = animator($("#wait"));
$("#start").click(animatedWait.start);
$("#stop").click(animatedWait.stop);
});
</script>
Here is a modified version that will turn off the dots after a time.
var count = 0;
var dots = setInterval(function(){
count++;
document.getElementById('loadingtext').innerHTML = "Waiting for your input." + new Array(count % 5).join('.');
if (count == 10){ // show two iterations of the array.
clearInterval(dots); // stop the dots.
}
}, 100); // sets the speed
http://jsfiddle.net/Ty4gt/331/

Categories