In this tutorial, you will learn how to change text on hover with random characters using JavaScript. Watch the video below for a detailed tutorial.
<body>
<h1 id="text">Lorem Ipsum</h1>
<script>
var text = document.getElementById('text'),
chars = '!@$%^&*()<>/abcdefghijklmnopqrstuvwxyz',
arrChars = text.innerHTML.split(''),
strCharSplit = '',
interval
function changeLetters(str) {
if(str.innerHTML !== ' ') {
str.innerHTML = chars[Math.floor(Math.random() * chars.length)]
}
}
for(i = 0; i < arrChars.length; i++) {
var strChar = arrChars[i]
strCharSplit = strCharSplit + "<span data-ltr='" + strChar + "'>" + strChar + "</span>"
}
text.innerHTML = strCharSplit
text.onmouseover = function() {
interval = setInterval(function() {
for(i = 0; i < text.childNodes.length; i++) {
changeLetters(text.childNodes[i])
}
}, 100)
}
text.onmouseout = function() {
clearInterval(interval)
for(i = 0; i < text.childNodes.length; i++) {
var letter = text.childNodes[i]
letter.innerHTML = letter.getAttribute('data-ltr')
}
}
</script>
</body>
body {
margin: 0;
background-color: #2e3537;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
h1 {
font-family: 'Arial', sans-serif;
font-size: 5em;
cursor: pointer;
color: white;
}