Rainbow Scrolling Text Using <span> - javascript

I would like to turn a small paragraph into rainbow text, in which the colors scroll from right to left in an infinite loop using JavaScript. I currently have this paragraph:
<div id="rainbow">
<p id="rtext">
<span id="s1" style="color: red">H</span>
<span id="s2" style="color: blue">e</span>
<span id="s3" style="color: green">l</span>
<span id="s4" style="color: purple">l</span>
<span id="s5" style="color: orange">o</span>
<span id="s6" style="color: magenta">!</span>
</p>
</div>
<div id="actbtn">
<button onclick="activ()">Click for RAINBOW!</button>
</div>`
I am fairly new to JavaScript so I am not sure how to write the activ() function to infinitely scroll the colors.
EDIT:
I would like to thank Ben for the looping script, but now I also need to know how to use the activ() function to change the color of a <span> element. I have tried the following script:
function activ() {
document.getElementById("s1").style.color = 'magenta';
}
But the color will not change. I am trying to keep the script as simple as possible, but also make it work.
FINAL EDIT:
I used Ivan's "UPD Without JQuery" code and added a few colors, and this is what I end up with:
<script>
function EyeVommit() {
document.getElementById("actbtn").style.display = 'none';
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta', 'chartreuse', 'cyan', 'yellow'],
target = document.getElementById('rtext').children,
i,
len = colors.length,
inter = setInterval(function() {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
target[i].style.color = colors[i];
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext"> <span id="s1">H</span><span id="s2">e</span><span id="s3">l</span><span id="s4">l</span><span id="s5">o</span><span id="s6">!</span>
<br />
<div id="actbtn">
<button onclick="EyeVommit()">Pabam!</button>
</div>
</p>
The result.

I'm begging you, never, never, never use it in design
<html>
<head>
<title>Price</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
function EyeVommit() {
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta'],
$target = $('#rtext span'),
counter,
i,
len = colors.length,
inter;
for (i = 0; i < len; i++) {
$target[i] = $($target[i]);
}
inter = setInterval(function () {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
$target[i].css('color', colors[i]);
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext">
<span id="s1">H</span>
<span id="s2">e</span>
<span id="s3">l</span>
<span id="s4">l</span>
<span id="s5">o</span>
<span id="s6">!</span>
</p>
</div>
<script>
EyeVommit();
</script>
</body>
</html>
UPD without jQuery
<script>
function EyeVommit() {
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta'],
target = document.getElementById('rtext').children,
i,
len = colors.length,
inter = setInterval(function () {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
target[i].style.color = colors[i];
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext">
<span id="s1">H</span><span id="s2">e</span><span id="s3">l</span><span id="s4">l</span><span id="s5">o</span><span id="s6">!</span>
<button onclick="EyeVommit()">Pabam!</button>
</p>
</div>

If by "Infinitely scroll" you mean create an infinite loop, you could do this.
function blaah(blaah){
//This is where you put all of your rainbow-y code
blaah("blaah");
}
Then you can just call the event through your button.
This code works because everytime the function runs, you call it again. (Second-last line of the function.)

Here's one that will work for any text that you put in the rtext block
Here is a codepen: http://codepen.io/anon/pen/GtwxD
Here's the HTML
<div id="rainbow">
<p id="rtext">Hello! This is some rainbow text!</p>
</div>
<div id="actbtn">
<button>Click for RAINBOW!</button>
</div>
This is the Javascript
$(document).ready(function(){
createSpans();
$('#actbtn').click(activ);
});
$rtxt = $('#rtext');
var text = $rtxt.html() , color;
function createSpans(){
$rtxt.html(' ');
window.colorCount = 0;
window.on = false;
colorPicker();
}
function activ(){
if(!window.on){
window.id = setInterval(colorPicker,100);
window.on = true;
}
else{
clearInterval(window.id);
window.on = false;
}
}
function colorPicker(){
$rtxt.html(' ');
window.colorCount++;
for(var letter = 0; letter < text.length; letter++){
switch ((letter + colorCount) % 6){
case 0 :
color = "red";
break;
case 1 :
color = "orange";
break;
case 2:
color = "green";
break;
case 3 :
color = "purple";
break;
case 4 :
color = "blue";
break;
case 5 :
color = "gold";
break;
default :
color = "black";
break;
}
$rtxt.append('<span style=" color:' + color + ';">' + text[letter] + '</span>');
}
}

Related

use location.hash to keep page status in javascript

I am doing a practice that use location.hash to keep page's state, what i have done using the below code is
1.click any button, the button's innerHTML will be written into the div#cont
2.refresh the page, it keeps the changes in the div#cont
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
And what i want to achieve next is add three other buttons(D,E,F) and a new div, when clicking one of the D\E\F, the innerHTMl will written into the new div.
The final goal is
click one of the A\B\C, the value will be written into 'contABC'
click one of the D\E\F, the value will be written into 'contDEF'
keep the changes when the page refresh
because this time it has to record two value, and i have no idea how to use hash to do that, anyone can help? Thanks in advance!
This is HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
Try by structuring the way you store the hash value , like using a separator -
<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash && location.hash.slice(1);
return hashValue && hashValue.split('-');
}
function draw() {
var cont = getHash();
if (cont && cont.length>0) {
document.getElementById('contABC').innerHTML = cont[0];
document.getElementById('contDEF').innerHTML = cont[1];
}
}
btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
var cont = getHash() || [];
if(btns[this.index].dataset.attr=='ABC'){
location.hash = btns[this.index].innerHTML + seperator + cont[1];
}else{
location.hash = cont[0] + seperator + btns[this.index].innerHTML ;
}
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>

Change text colors every second

HTML Code
function changeColor() {
var x = document.getElementById("li1");
x.style.color = "blue";
if (x.style.color == "blue") {
x.style.color = "yellow";
}
}
window.setInterval("changeColor", 1000);
<body>
<div class="leftDiv">
<div id="stepsId">
<ol>
<li id="li1"><b>Step 1</b></li>
<li id="li2"><b>Step 2</b></li>
<li id="li3"><b>Step 3</b></li>
</ol>
</div>
</div>
</body>
My main goal is to cycle through the colors from steps 1 to 3 with each step turning blue > yellow > blue > yellow every second in ascending order. I cannot figure out what am I doing wrong.
Your existing JS doesn't work because you left the closing } off your function, and because in the call to setInterval() the function name in the first argument should not be in quotes (that is, pass a function reference, not a string).
But also, your code only references the first element in the list, and you said you want to change "each step...in ascending order". So maybe you could do something like the following, using document.querySelectorAll("#stepsId li") to select all of the li elements, then loop over them to change their colours in sequence:
var colors = ["blue", "yellow"]
var currentColor = 0
var lis = document.querySelectorAll("#stepsId li")
function changeColor() {
--currentColor
if (currentColor < 0) currentColor = colors.length -1
for (var i = 0; i < lis.length; i++) {
lis[i].style.color = colors[(currentColor +i) % colors.length]
}
}
setInterval(changeColor, 1000)
<div id="stepsId">
<ol>
<li id="li1"><b>Step 1</b></li>
<li id="li2"><b>Step 2</b></li>
<li id="li3"><b>Step 3</b></li>
</ol>
</div>
Note that you can add any number of colours into the array and it will cycle through all of them:
var colors = ["blue", "yellow", "red", "green", "orange"]
var currentColor = 0
var lis = document.querySelectorAll("#stepsId li")
function changeColor() {
--currentColor
if (currentColor < 0) currentColor = colors.length -1
for (var i = 0; i < lis.length; i++) {
lis[i].style.color = colors[(currentColor +i) % colors.length]
}
}
setInterval(changeColor, 1000)
<div id="stepsId">
<ol><li id="li1"><b>Step 1</b></li><li id="li2"><b>Step 2</b></li><li id="li3"><b>Step 3</b></li></ol>
</div>
To achieve expected result, use below option
1.Initialize color outside function
2.toggle color using setInterval
Codepen URL for reference- http://codepen.io/nagasai/pen/NjWBxv
JS:
var x = document.getElementById("li1");
x.style.color = "blue";
function changeColor(){
x.style.color = x.style.color == "blue"?"yellow":"blue";
}
window.setInterval(changeColor,1000);
There are few syntax errors like missing close '}' and remove quotes for function as it is not a string
Here is working code
<html>
<head>
<script type="text/javascript">
var x = setInterval(function() {
console.log('rrr');
var x = document.getElementById("li1");
x.style.color = "blue";
if (x.style.color == "blue"){
x.style.color = "yellow";
}
}, 1000);
</script>
</script>
<body>
<div class="leftDiv">
<div id = "stepsId" >
<ol>
<li id="li1"><b>Step 1</b></li>
<li id="li2"><b>Step 2</b></li>
<li id="li3"><b>Step 3</b></li>
</ol>
</div>
</div>
</body>
</html>
This works
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
var x = document.getElementById("li1");
x.style.color = "blue";
function changeColor(){
if (x.style.color == "blue"){
x.style.color = "yellow";
}
else if (x.style.color == "yellow"){
x.style.color = "blue";
}
};
window.setInterval(changeColor,1000);
};
</script>
</head>
<body>
<div class="leftDiv">
<div id = "stepsId" >
<ol>
<li id="li1"><b>Step 1</b></li>
<li id="li2"><b>Step 2</b></li>
<li id="li3"><b>Step 3</b></li>
</ol>
</div>
</div>
</body>
</html>
You're only trying to change li1, rather than all of the li elements, which I assume is your intention. Try using document.querySelectorAll instead of document.getElementById and then iterating through the array, like so
function changeColor() {
var x = document.querySelectorAll("#stepsId li");
for (var i = 0; i < x.length; i++) {
x[i].style.color = x[i].style.color === 'blue' ? 'yellow' : 'blue';
}
}
window.setInterval(changeColor, 1000);
This answer assumes that you want them all changing to the same color at the same time.
Refer this code
<html>
<head>
<script type="text/javascript">
var i = 1;
var x = setInterval(function() {
var x = document.getElementById("li1");
console.log(x.style.color);
if (x.style.color == "blue"){
x.style.color = "yellow";
} else if (x.style.color === "yellow"){
x.style.color = "red";
} else if (x.style.color === "red"){
x.style.color = "blue";
}
}, 1000);
</script>
</script>
<body>
<div class="leftDiv">
<div id = "stepsId" >
<ol>
<li id="li1" style="color: blue;"><b>Step 1</b></li>
<li id="li2"><b>Step 2</b></li>
<li id="li3"><b>Step 3</b></li>
</ol>
</div>
</div>
</body>
</html>
Two things to consider first:
The JavaScript you posted is not syntactically valid because you fail to close your if statement curly brace (the "}").
The code inside your function will quickly. The only color change that you will see on the page is the final color value when your function finishes.
You will need to keep track of which element is yellow at any particular point and set up your function to determine which element should be turned yellow next.
var li1 = document.getElementById("li1");
var li2 = document.getElementById("li2");
var li3 = document.getElementById("li3");
var yellow = li1;
function changeColor() {
if(li1 == yellow) {
yellow = li2;
} else if(li2 == yellow) {
yellow = li3;
} else {
yellow = li1;
}
li1.style.color = "blue";
li2.style.color = "blue";
li3.style.color = "blue";
yellow.style.color = "yellow";
}
window.setInterval(changeColor, 1000);
This is how you can achieve a cycle! But be careful while selecting lis, beacuse I just used getElementsByTagName which will give you all the li element
var lis = document.getElementsByTagName("li");
var i = 0
var color ='blue'
function changeColor(){
if(i==3){
i=0
}
lis[i].style.color = color;
if (lis[i].style.color == "blue"){
color = 'yellow'
}
else{
color = 'blue'
}
i = i+1;
}
window.setInterval(changeColor,1000);
<html>
<body>
<div class="leftDiv">
<div id = "stepsId" >
<ol>
<li id="li1"><b>Step 1</b></li>
<li id="li2"><b>Step 2</b></li>
<li id="li3"><b>Step 3</b></li>
</ol>
</div>
</div>
</body>
</html>

How to append a method to my button?

I have a function called getRandomColor() and I want to apply this method to my button in the HTML doc. So, when you click the button it changes the entire body's color.
This is the javascript code:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
This is the HTML code for the button and my attempt to apply the JS code:
<div class="row">
<div class="col-6-xs">
<button onclick="getRandomColor()"id="quotes"type="button" class="right-btn pull-right btn btn-success">Get Quotes</button>
</div>
Right away, I can tell that clicking the button won't change the document's color. I was thinking of adding this code to the getRandomColor() method:
document.body.style.background = color;
However, it still doesn't change the document color.
Actually the code you submitted, does seem to work, the only thing you might need to do is at the end of the function, apply the color to the DOM
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
document.body.style.background = color;
}
<body>
<div class="row">
<div class="col-6-xs">
<button onclick="getRandomColor()"id="quotes"type="button" class="right-btn pull-right btn btn-success">Get Quotes</button>
</div>
</div>
</body>

animate elements in random sequence

I try to animate some buttons. A random string should be generated that the animated buttons arent always in the same sequence. fiddle
an example:
text = 1423
the first animated button is btn1 then after one second btn4 then after one second btn2 then after one second btn3
the buttons:
<div>
<button name="btn1" type="submit" id="btn1" value="1" style="" class="button"></button>
<button name="btn2" type="submit" id="btn2" value="2" style="" class="button"></button>
</div>
<div>
<button name="btn3" type="submit" id="btn3" value="3" style="" class="button"></button>
<button name="btn4" type="submit" id="btn4" value="4" style="" class="button"></button>
</div>
the javascript:
var textArray = [];
var text = "";
function makeid()
{
var possible = "1234";
for( var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
makeid();
textArray = text.split("");
console.log(textArray);
function animate1() {
$('#btn' + textArray[0]).animate( { backgroundColor: 'red' }, 500);
}
function animate2() {
$('#btn' + textArray[1]).animate( { backgroundColor: 'red' }, 500);
}
function animate3() {
$('#btn' + textArray[2]).animate( { backgroundColor: 'red' }, 500);
}
function animate4() {
$('#btn' + textArray[3]).animate( { backgroundColor: 'red' }, 500);
}
window.setTimeout(animate1, 1000);
window.setTimeout(animate2, 2000);
window.setTimeout(animate3, 3000);
window.setTimeout(animate4, 4000);
Your issue about shuffling the possible text, because in your function there is a possibility that same number repeated. like: 2,2,2,1 or 4,4,4,4 and so on.
you can use this shuffle function instead of your method of shuffling:
function shuffleWord(word) {
var shuffledWord = '';
var charIndex = 0;
word = word.split('');
while (word.length > 0) {
charIndex = word.length * Math.random() << 0;
shuffledWord += word[charIndex];
word.splice(charIndex, 1);
}
return shuffledWord;
}
See JsFiddle of your example after updates.
You can't animate backgroundColor unless the jQuery.Color plugin is used, jQuery animate docs
All animated properties should be animated to a single numeric value,
except as noted below; most properties that are non-numeric cannot be
animated using basic jQuery functionality (For example, width, height,
or left can be animated but background-color cannot be, unless the
jQuery.Color plugin is used).
And you allow duplicate IDs when creating the random order. Also, the code can be simplified.
var textArray = [];
function makeid() {
var num;
var possible = "1234";
while(textArray.length < 4) {
num = possible.charAt(Math.floor(Math.random() * possible.length));
if (textArray.indexOf(num) === -1) {
textArray.push(num)
}
}
}
function animate(id, wait) {
setTimeout(function() {
$('#btn' + id).animate({ width: '200'}, 500);
}, wait);
}
makeid();
for (var i=0; i < textArray.length; i++) {
animate(textArray[i], i * 1000)
}
fiddle

button checking a checkbox using javascript

I am trying to make a button that will toggle between three colors: black, green, and red and will either check a certain box depending on the color. Right now I can make the color toggle but I can't make the check boxes check. I would appreciate the help. I am a beginner (obviously).
Button color green: check box 1
Button color red: check box 2
Button color black: do not check either box 1 or 2
The script looks like:
<script>
var colors = ["green", "red", "black"]
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
}
</script>
The HTML looks like:
<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />
</html>
Thanks!
I'd suggest:
var colors = ["green", "red", "black"];
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
document.getElementById('box1').checked = el.style.color == 'green';
document.getElementById('box2').checked = el.style.color == 'red';
}
JS Fiddle demo.
Do it like this:
var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
document.getElementById("box1").checked = false;
document.getElementById("box2").checked = false;
}
else if( index == 0 )
{
document.getElementById("box1").checked = true;
}
else
{
document.getElementById("box2").checked = true;
}

Categories

Resources