CodeLab
Tutorials For Everyone
Run
<!DOCTYPE html> <html> <head> <title>JavaScript Coding Tutorial - Tuts Insider</title> </head> <body> <h3 id="shuffleString" style="letter-spacing: 2px; margin-bottom: 10px; margin-top: 60px;">Learn JavaScript</h3> <div><button id="shuffleButton" style="padding: 5px;">Shuffle Colors</button> <div>Shuffle the letter colors by clicking the button.</div> </div> <script> /* ********************************************** * Shuffle the Letter Colors With Button Click ********************************************** */ function generateRandomColor() { var letters = "0123456789ABCDEF"; var color = "#"; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } // function to shuffle colors of the string function shuffleLetterColors() { var str = document.getElementById("shuffleString").textContent; var result = ""; for (var i = 0; i < str.length; i++) { if (str[i] == ' ') { result += "<span style='color:#ffffff; border-top: 50px solid;'>" + str[i] + "</span>"; } result += "<span style='color:" + generateRandomColor() + "; border-top: 50px solid;'>" + str[i] + "</span>"; } document.getElementById("shuffleString").innerHTML = result; } // on page load, call shuffleLetterColors function twice with 1 second interval window.onload = function () { shuffleLetterColors(); } // on button click, call shuffleLetterColors function var shufflebutton = document.getElementById("shuffleButton"); shufflebutton.addEventListener("click", shuffleLetterColors); </script> </body> </html>