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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With