Search code examples
javascripthtmlcsstagstextcolor

HTML randomize inline text block space and color


Currently I have some texts flying over a background video. The text color and the space in between two text blocks are fixed. What I want to achieve is to randomize both the color and space for each text block in run time. I believe it can be achieved using javascript but I'm not exactly sure how. Here is my current HTML and CSS code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demo</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="StyleSheet.css"/>
</head>
<body>
<iframe width="100%" height="315" src="http://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1"></iframe>
<div class="marquee">
    <span>yay 1st comment</span>
    <span> </span>
    <span>lol</span>
    <span> </span>
    <span>hacking !!???</span>
    <span> </span>
    <span>this video is hacked!!!!!</span>
    <span> </span>
    <span>this is THE 4th dimension hahaha</span>
    <span> </span>
    <span>Let's use this feature more wisely now</span>
    <span> </span>
    <span>Okay</span>
    <span> </span>
</div>
</body>
</html>

StyleSheet

* {
    margin: 0;
    padding: 0;
}

html, body {
    width: 100%;

}

.marquee {
    color: white;
    position: absolute;
    margin-top: 20px;
    top: 0;
    animation: marquee 20s linear infinite;
    z-index: 1;
    display: inline-block;
}

span:before{
    content:" ";
    display:inline-block;
    width:32px;
}

/* Make it move */
@keyframes marquee {
    0%   { text-indent: 100em }
    100% { text-indent: -100em }
}

Should I do something in javascript along the line of this?

var comments = document.getElementsByTagName("span");
for (var i = 0; i < comments.length; i++) {
    comments[i].setAttribute("color", getRandomColor())
}

But somehow this doesn't work.


Solution

  • to change color use

    for (var i = 0; i < comments.length; i++) {
        comments[i].style.color = getRandomColor();
    }

    Edit: to randomize space use

    span.style.paddingRight = getRandomSpace() + "px";
    

    Edit2: As @dandavis pointed out in the comment above, "instead of random colors, it would look a LOT nicer to pre-bake 5-10 pairs of good readable colors and randomly choose from the pairs"