Lucas Debelder Lucas Debelder - 20 days ago 5
CSS Question

HTML/CSS/JS - How can I change text using a setInterval?

I'm trying to recreate something like you can see on https://www.sketchapp.com/, midway through the page the text changes automatically (Sketch is made for UX designers like you). I have searched a bit but couldn't find exactly how to make something like that. This is what I got, if theres anyone who can help me, that would be awesome, Thanks!



document.addEventListener('DOMContentLoaded', function(){
setTimeout(function(){
var div = document.getElementById('js-text');
div.innerHTML = "Replaced <span class='redText'>Text</span>";
}, 1000);
});

.redText{
color: red;
}

<div id="js-text">Initial Text</div>




Answer

How about this solution. Hope it helps!

$(document).ready(function(){
  $("#test").html("<div>"+ 'Sketch is made for UI designers like you'+"</div>").fadeTo(100, 0.1).fadeTo(200, 1.0);
   var str = "";
   var number = 1;
   var timer = setInterval(function() {
    if(number == 0){str = "Sketch is made for" +'<span class = "myClass"> UI </span>' + "designers like you"}
     if(number == 1){str = "Sketch is made for" +'<span class = "myClass"> UX </span>' + "designers like you"}
     else if(number == 2){str = "Sketch is made for"+'<span class = "myClass"> web designers </span>'+ "like you"}
     else if(number == 3){str = "Sketch is made for" + '<span class = "myClass"> mobile designers </span>'+ "like you"} 
     $("#test").html("<div>"+ str+"</div>").fadeTo(100, 0.1).fadeTo(200, 1.0);
     ++number;
     if(number == 4){
        number = 0;
     }
    }, 2000); 
});
.myClass{
  background: purple;
  color: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id = "test">
</div>