Jquery Animating between colours - javascript

Fairly rudimentary question. If I have a random number variable which picks a random selection out of an array for example "red" I want to be able to store that as the current color whilst it picks a new colour after 5 seconds and then animate from the current colour "red" to the new colours for example "green" so it fades the background or body of the document slowly from one to the other.
I have some code that I have written so far but I am unsure how I would get this, I know I would have to store the current color if it was found then find the next color but Im not sure how.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Roger</title>
<link rel="stylesheet" href="Roger.css"/>
<script src="jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="Roger.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<!-- end .container --></div>
</body>
<script>
var Colours = [];
var randCol;
var curCol;
Colours[0] = "red";
Colours[1] = "green";
Colours[2] = "blue";
Colours[3] = "black";
Colours[4] = "grey";
window.setInterval(function(){
randCol = Math.floor(Math.random() * 5) + 0
alert(randCol);
var nextCol= Colours[randCol];
if(Colours[randCol] == Colours[0]) {
document.body.style.backgroundColor="red";
curCol = "red";
}
else if(Colours[randCol] == Colours[1]) {
document.body.style.backgroundColor="green";
curCol = "green";
}
else if(Colours[randCol] == Colours[2]) {
document.body.style.backgroundColor="blue";
curCol = "green";
}
else if(Colours[randCol] == Colours[3]) {
document.body.style.backgroundColor="black";
curCol = "black";
}
else if(Colours[randCol] == Colours[4]) {
document.body.style.backgroundColor="grey";
curCol = "grey";
}
}, 5000);
</script>
</html>

I'd try something more like this
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Roger</title>
<link rel="stylesheet" href="Roger.css" />
<script src="jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="Roger.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<!-- end .container -->
</div>
<script>
var Colours = [
"red",
"green",
"blue",
"black",
"grey"
],
prevCol = null;
window.setInterval(function () {
var randCol = Math.floor(Math.random() * Colours.length)
while (randCol === prevCol) randCol = Math.floor(Math.random() * 5);
prevCol = randCol;
document.body.style.backgroundColor = Colours[randCol];
}, 5000);
</script>
</body>
</html>
FIDDLE
To animate colors with jQuery you'll need a plugin, it that's what you're going to next ?

To do the fading from one color to the other without additional plugins, you could set the start background color to the body, the end background color to the .container and then incrementally change the opacity of the .container from 0 (transparent) to 1 (visible) using setInterval or setTimeout function.

Related

Style each letter in a string with a random color/size on click of button

I need to design a JavaScript script that writes a given text string to the screen so that the size and color of each character is set up randomly, using at least 7 colors and 5 sizes. I am able to get the string of text to randomly change color and size, but I can't seem to get it to work for each individual letter. I've included my code, and the code commented out is what I've tried but doesn't work.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1 id="header" name="header" value="">JavaScript is fun!</h1>
<button type="button" onclick="randomizeText()">Randomize!</button>
<script language="JavaScript">
// <!--
function generateRandomColor() {
var colors = ["green", "blue", "red", "yellow", "cyan", "orange", "magenta"];
var randomColor = colors[Math.floor(Math.random() * colors.length)];
return randomColor;
};
function generateRandomFontSize() {
var sizes = ["12px", "14px", "16px", "18px", "20px"];
var randomSize = sizes[Math.floor(Math.random() * sizes.length)];
return randomSize;
};
function randomizeText() {
document.getElementById("header").style.color = generateRandomColor();
document.getElementById("header").style.fontSize = generateRandomFontSize();
// var newHeaderText = "";
// for (var i = 0; i < headerText.length; i++) {
// var letter = headerText.charAt(i);
// // letter.style.fontSize.generateRandomFontSize();
// // letter.style.color.generateRandomColor();
// // newHeaderText = newHeaderText.concat(letter);
// }
// document.write(newHeaderText);
};
// document.getElementById("header").innerHTML = headerText;
// Javascript ends here-->
</script>
</body>
</html>
split and join the string, wrapping each letter with a span. Then you can assign different color to each of these spans.
function generateRandomColor() {
var colors = ["green", "blue", "red", "yellow", "cyan", "orange", "magenta"];
var randomColor = colors[Math.floor(Math.random() * colors.length)];
return randomColor;
};
function generateRandomFontSize() {
var sizes = ["12px", "14px", "16px", "18px", "20px"];
var randomSize = sizes[Math.floor(Math.random() * sizes.length)];
return randomSize;
};
function randomizeText() {
var elem = document.getElementById("header")
elem.style.color = generateRandomColor();
elem.style.fontSize = generateRandomFontSize();
elem.innerHTML = span_it(elem.innerText);
// now each letter
var spans = elem.querySelectorAll("span");
spans.forEach(span => span.style.color = generateRandomColor())
};
function span_it(str) {
return str.split("").map(letter => "<span>" + letter + "</span>").join("")
}
<h1 id="header" name="header" value="">JavaScript is fun!</h1>
<button type="button" onclick="randomizeText()">Randomize!</button>

Made a colorcyle using js and want to terminate it's execution on the event of a click on the stop button

Here's my code
var stop = document.querySelector('#stop');
var begin = document.querySelector('#start');
function rainbow() {
var colors = ['red', 'orange', 'blue', 'green', 'yellow', 'violet'];
var i = 0;
setInterval(function() {
document.body.style.backgroundColor = colors[i];
i++;
i = i % colors.length;
}, 1000);
}
begin.addEventListener('click', function() {
rainbow()
});
function noColor() {
document.body.style.backgroundColor = 'white';
}
stop.addEventListener('click', function() {
noColor()
});
<!DOCTYPE html>
<html>
<head>
<title>JS homework</title>
</head>
<body>
<div class="wrapper"></div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<script src="j1.js"></script>
</body>
</html>
Although it does switch the bgcolor to white but it begins the rainbow() all over again.
I came across another interesting anomaly (if I could say so). Whenever I click on the stop button it changes the bgcolor to white but resumes from the color that was to appear from the array. For eg if I click stop after red, it would resume with orange
It happens because the interval keeps running. You should clear it.
Use clearInterval and pass to it the interval you wish to cancel.
var stop = document.querySelector('#stop');
var begin = document.querySelector('#start');
let interval;
function rainbow() {
var colors = ['red', 'orange', 'blue', 'green', 'yellow', 'violet'];
var i = 0;
interval = setInterval(function() {
document.body.style.backgroundColor = colors[i];
i++;
i = i % colors.length;
}, 1000);
}
begin.addEventListener('click', function() {
rainbow()
});
function noColor() {
document.body.style.backgroundColor = 'white';
clearInterval(interval);
}
stop.addEventListener('click', function() {
noColor()
});
<!DOCTYPE html>
<html>
<head>
<title>JS homework</title>
</head>
<body>
<div class="wrapper"></div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<script src="j1.js"></script>
</body>
</html>

Stuck on unexpected container childnodes - javascript HTML

Can anyone help me on Javascript coding? Lines13-14 i try to create 9x div(class="square") but i get 18 childnodes when i check container from console. It also prints 18 in total?
Second issue is about resetbutton. When i try to clear container childnodes to start a new game it gives error. (maybe there's no need to add some code to clear container?) Thank you.
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
function newGame () {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for(let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for(let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
/// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
For the first problem of having 18 divs instead of 9 in is because newGame method is called twice. One is at the end of code, the other one is in this line:
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
The resetGame method is called there but it should be just passed as it is:
buttonReset.addEventListener("click", resetGame);
For the second problem of resetGame method not working as expected is that you are modifying the array that is being accessed (container.childNodes) in the loop.
That makes your i skip the element next to the each removed one.
Your difficulty may eventually become larger than childNodesCount
One solution is that do not remove items immediately, accumulate them in an array array and then remove based on that array
const toBeRemoved = []
for (let i = 0; i < difficulty; i++) {
toBeRemoved.push(container.childNodes[i]);
}
toBeRemoved.forEach(child => {
container.removeChild(child);
})
OR, another solution is that copy the childNodes to another variable so when you modify the original childNodes the copied array does not get affected:
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
After fixing both problems:
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame);
function newGame() {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for (let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for (let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame() {
/// Clean boxes
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

how to change div color when an even "mouseover " has been trigged on that same div? pure JS

var changeDiv = document.getElementsByClassName("run")[0];
function changeColor(style) {
var colors = ["green", "blue", "yellow"];
for (var i = 0; i < colors.length; i++) {
style.style.backgroundColor = colors[i];
break;
}
}
changeDiv.addEventListener("mouseover", function() {
changeColor(this);
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="run">
e3reerghdhf </b>
djdhfdgfdgdhhghgd
</div>
</body>
</html>
I want to change to one color and I want to hover over the div and change its color, everytime I hover or (mouseover). I thought that maybe i had to use windowSessionStorage to hold the index and change its value if the event is triggered.
You can store the variables in js, like so:
var changeDiv = document.getElementsByClassName("run")[0];
var colors = ["green", "blue", "yellow"];
var i = 0;
function changeColor(style) {
style.style.backgroundColor = colors[i];
if (i < colors.length - 1) {
i++
}
else {
i = 0;
}
}
changeDiv.addEventListener("mouseover", function() {
changeColor(this);
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="run">
e3reerghdhf </b>
djdhfdgfdgdhhghgd
</div>
</body>
</html>
Here's a solution that progresses through different background colors and resets to the original background when not being hovered.
function colorChange( el, colors ) {
var i = 0,
baseColor = el.style.backgroundColor;
el.addEventListener( 'mouseenter', function () {
this.style.backgroundColor = colors[ i++ % colors.length ];
} );
el.addEventListener( 'mouseleave', function () {
this.style.backgroundColor = baseColor;
} );
}
var colors = [ 'red', 'blue', 'yellow' ];
var p = document.querySelector( 'p' );
colorChange( p, colors );
<p>Hello world!</p>
You can definetly implement that behaviour using Javascript, but why would you want to implement something that can easilly be done using a single line of basic CSS ?
.run:hover{ background-color:red;}
EDIT:
Change color on each rollover, using list of colors.
You can use the array and a index pointer, and increment the pointer each time the event is triggered:
https://jsfiddle.net/ydrr0xn8/
var changeDiv = document.getElementsByClassName("run")[0];
changeDiv.addEventListener("mouseover", function() {
var colors = ['red', 'green', 'blue'];
var index = colors.indexOf(changeDiv.style.backgroundColor) + 1;
if (index >= colors.length || index === -1) index = 0;
changeDiv.style.backgroundColor = colors[index];
}, false);
<div class="run">ff</div>

Progress bar not working in html file

I am creating a progrees bar is it working fine in jsfiddle demo but when i use in html file it is not working here is my code
i am writing same code as given in jsfiddle but it is not working
<html>
<head>
<style>
.ui-progressbar.beginning .ui-progressbar-value { background: red; }
.ui-progressbar.middle .ui-progressbar-value { background: yellow; }
.ui-progressbar.end .ui-progressbar-value { background: green; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
var $progressbar = $("div").progressbar();
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar
.progressbar("value", value)
.removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
var $progressbar = $("div").progressbar();
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar
.progressbar("value", value)
.removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
</script>
</head>
<body onload="update()">
<div>
</div></body></html>
and here is js fiddle link working
http://jsfiddle.net/ZQrnC/305/
Look in the left sidebar of jsfiddle below "External Resources". You are embedding the jQuery UI css and js for your progressbar() there, but your html file jQuery UI is missing.
Add the following after your jquery-1.9.1.js-script-tag:
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
There are three reasons why it does not work:
As robbi5 stated you don't import the jquery ui JS and CSS files
Your var $progressbar is initialized in the header when the page is not already loaded and so no div can be found. In other words $progressbar points on nothing
Your progress bar has an height of zero making it invisble, you should wrap him a container div with a fixed height
Also your code contains duplicate part but it may due to a wrong copy/paste.
Here is an updated working version of your page with the corrected points. I checked rapidly only on chrome and firefox and it works.
<html>
<head>
<style>
.ui-progressbar.beginning .ui-progressbar-value { background: red; }
.ui-progressbar.middle .ui-progressbar-value { background: yellow; }
.ui-progressbar.end .ui-progressbar-value { background: green; }
</style>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script src=" http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
</head>
<script>
var $progressbar;
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar.progressbar("value", value).removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
$progressbar = $("#pbholder").progressbar();
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
</script>
</head>
<body onload="update()">
<div id="container" style="height:50px">
<div id="pbholder">
</div>
</div>
</body></html>

Categories

Resources