Changing color code doesn't work - javascript

function color(){
var color = "#"
for(var i = 0; i<6; i++){
color += Math.floor((Math.random()*16)).toString(16);
};
document.getElementsByTagName('body')[0].style.backgroundColor = color;
}
function change(){
setInterval(color(), 1000);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='button' onmouseover="change();" style='width:50px; height:50px; margin-left:auto;'>click</button>
<script type="text/javascript" src='js.js'></script>
</body>
</html>
I tried to make the auto changing background coding.
I want to change the background color every 1 second.
but it just change color once when i put my mouse on.
what is the problem?

You're calling the function, not referencing it in the setInterval call.
Change it to
setInterval(color, 1000);
FIDDLE
When you add the parentheses to a function, it's called, and the returned result, which is always undefined unless something else is defined in the called function, will be returned.
What you're doing is the same as
var fn = color(); // returns undefined
setInterval(fn, 1000); // undefined, 1000

Here's a working snippet.
What I changed was
onmousehover was replaced with oneclick() (since it says click on the button)
In the setInterval function call, color doesn't need the brackets
function color(){
var color = "#"
for(var i = 0; i<6; i++){
color += Math.floor((Math.random()*16)).toString(16);
};
document.getElementsByTagName('body')[0].style.backgroundColor = color;
}
function change(){
setInterval(color, 1000);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='button' onclick="change();" style='width:50px; height:50px; margin-left:auto;'>click</button>
<script type="text/javascript" src='js.js'></script>
</body>
</html>
</html>

Here is a working example
<body>
<button id='button' onmouseover="change()" style='width:50px; height:50px; margin-left:auto;'>click</button>
</body>
<script>
function color() {
var color = "#"
for (var i = 0; i < 6; i++) {
color += Math.floor((Math.random() * 16)).toString(16);
};
document.getElementsByTagName('body')[0].style.backgroundColor = color;
}
function change() {
setInterval(color(), 1000);
}
</script>
Fiddle: https://jsfiddle.net/9cxw9jL0/

I have changes some code and you can find in plunker.
<https://plnkr.co/edit/sKpJQqRohICD63AQjgTx?p=preview>

Here is the solution for your problem
function colorchanger(){
setInterval(function(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
document.body.style.backgroundColor = color;
},300);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<button onclick="colorchanger();" >Change Color</button>
</body>
</html>

Related

How to update a JavaScript generated HTML variable

I created this little background color changer just for fun and to play around with JS for a bit but I'm having a problem I don't really know how to solve.
This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Color picker</title>
</head>
<body>
<div class="container d-flex align-items-center justify-content-center">
<div>
<button id="main_button" class="btn btn-danger">Change color</button>
</div>
</div>
</body>
</html>
and my JS:
const button = document.querySelector("#main_button");
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function changeBackground(){
document.body.style.backgroundColor = randomColor();
};
function createParagraph(){
let color = randomColor();
const div = document.querySelector(".container");
let par = document.createElement("p");
par.innerHTML = "Current color is " + color;
div.appendChild(par);
}
button.addEventListener("click", changeBackground);
button.addEventListener("click", createParagraph);
And this is my problem, every time I click on the button a new paragraph is being generated with the new color code. But I want the button to update the color code in the same paragraph.
on every click you are adding another p tag - instead create a p tag in your html page-
<p id="colorTag"><p>
in your createParagraph function -
instead of let par = document.createElement("p"); do let par = document.getElementById('colorTag') par.innerHTML = "Current color is " + color;
You are actually creating a new <p>-element every time you call createParagraph().
Instead, you can create a tag in your HTML beforehand, and save its reference (which you can get by querying for it using e.g. document.querySelector()) in a variable.
Then, you can change its content by assigning a new value to its .textContent-property.
Here a demonstration:
var pElement = document.querySelector('#p-id');
document.querySelector('button').addEventListener('click', () => {
pElement.textContent = "This is its new text, assigned using the '.textContent'-property!";
});
<button>Change <p>'s content!</button>
<p id="p-id">This is the initial text.</p>
An important note would be, that you are actually not displaying the current color-value. You are calling randomColor() twice: Once in changeBackground(), and once in createParagraph(), while the created color is only used for either assigning <body> a new background-color or being displayed using the <p>-tag.
To display the actually used color, you need to use the same String for both the assignment and the value of <p>'s content. You can do that by one of the following:
Write both use-cases in one function
Use another variable for the color
Use the value of document.body.style.background (or .backgroundColor, depending on what you used). However, this will return the color in a format like rgb(123, 213, 132), which might be unwanted.
I'll show examples for points 1 and 2.
Point 1 could look like this:
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeAndUpdateColor() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
}
button.addEventListener('click', changeAndUpdateColor);
<button id="main_button">Change Color</button>
<p id="p_id"></p>
Point 2 could look like this:
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
var color = '';
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeBackground() {
document.body.style.background = color;
}
function updateParagraph() {
pElement.textContent = 'Current Color is ' + color;
}
function getNewColor() {
color = randomColor();
}
button.addEventListener('click', getNewColor);
button.addEventListener('click', changeBackground);
button.addEventListener('click', updateParagraph);
<button id="main_button">Change Color</button>
<p id="p_id"></p>
However, using this many functions and listeners makes the code look clunky. Instead, you should make use of ES6's function expressions or arrow function expressions.
When using a function expression, we can initialize and use the color-variable inside, making a global variable useless.
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
button.addEventListener('click', function() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
});
<button id="main_button">Change Color</button>
<p id="p_id"></p>
Speaking of global context:
Declaring many variables and/or functions in the global context will pollute the global namespace, and will be accessible to the user e.g. using the browser-console. This is a problem for functions where sensitive data is handled or accessible.
To free up the global namespace, we can place most of our script inside a so called IIFE, an immediately invoked function expression. Adding this would be as simple as placing your code inside one like this:
(function() {
// Your code ...
})();
The brackets around the function expression itself will group it so it can be executed using the calling brackets (), much like placing a number inside brackets will allow us to call a function on it, like this:
(123).toString();
One further note now would be, that function declarations inside blocks (means: when not declared in the global context) are not part of ECMAScript, making this a non-standardized feature. This might be irrelevant to you, since it is supported in most (if not all) modern browsers anyway. However, in these cases, one should use function expressions referenced by a variable, e.g. like this:
(function() {
var aFunction = function() {
// ...
};
aFunction(); // Executed as usual
})();
Note that function expressions are not hoisted, unlike function declarations, meaning they need to come before their usage in the code.
Accessing characters of a String like accessing entries of an array is another non-standardized feature, again supported in most browsers. The standardized way would be to use String.charAt().
Refactoring your code could look like this:
// Is OK to be globally accessible
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters.charAt(Math.floor(Math.random() * 16));
}
return color;
}
// Should be placed inside an IIFE; the global context is still accessible
(function() {
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
button.addEventListener('click', function() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
});
})();
<button id="main_button">Change Color</button>
<p id="p_id"></p>
If I understand you correctly, then you want to change the backgroundcolor to the newest paragraph color. Therefor you have to call the changebackground function in the createParagraph function:
function createParagraph(){
let color = randomColor();
const div = document.querySelector(".container");
let par = document.createElement("p");
par.innerHTML = "Current color is " + color;
div.appendChild(par);
changeBackground(color);
}
function changeBackground(newcolor){
document.body.style.backgroundColor = newcolor;
};
button.addEventListener("click", createParagraph);
This would do the job.
You every time create a new paragraph -
HTML File :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-
beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-
giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous"
/>
<title>Color picker</title>
</head>
<body>
<div class="container d-flex align-items-center justify-content-center">
<div>
<button id="main_button" class="btn btn-danger">Change color</button>
</div>
<p id="par"></p> <!-- <== You Need this for render every time color -->
</div>
<script src="./script.js"></script>
</body>
</html>
JS File:
const button = document.querySelector("#main_button");
function randomColor() {
let letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeBackground() {
document.body.style.backgroundColor = randomColor();
}
function createParagraph() {
let color = randomColor();
const div = document.querySelector(".container");
let par = document.getElementById("par"); // select paragraph as html file
par.innerHTML = "Current color is " + color; // and render color to paragraph
}
button.addEventListener("click", changeBackground);
button.addEventListener("click", createParagraph);

how to add animation in string

I want add rotation in my string for that i have set interval but its not getting me as i want. it works only for one time when i reload the browser. So what should i add for continuing the function.
this is my code
HTML
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body onload="shubham()">
<div id="target">w3resource</div>
<button >click</button>
</body>
</html>
javascript
function shubham()
{
var x=document.getElementById('target').textContent;
var y=x.split('');
var z=y[0];
var m=y[y.length-1];
setInterval(function ()
{
document.getElementById('target').innerHTML = m+x.substring(0,8);
},500);
}
The problem with your code was that the variables were initialized once, and whenever, the setInterval function was called, there was no change in variables and hence the result remained the same which appeared as function only executed 1 time only.
Move your variables inside the setInterval function.
setInterval(function() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
<div id="target">w3resource</div>
you mean something like this
<html>
<head>
<title>JavaScript basic animation</title>
</head>
<body onload="shubham()">
<div id="target">w3resource</div>
<button onclick="shubham()">click</button>
</body>
</html>
<script>
function shubham() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
setInterval(function () {
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
}
</script>

Fadein in slider doesnt work

Why is it omitting the last slide? How can I fix it to show the first image just after the side loads, without waiting? I've tried everything and cant fix it out, always were some problems (displaying two images at the same time etc) and now this.
<!DOCTYPE html>
<html lang="pl">
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://use.fontawesome.com/19445204e2.js"></script>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
// Startowy slajd
var numer = 0;
function changeslide()
{
var imagesnumber=document.getElementById("slider").getElementsByTagName("img");
for(var i = 0; i < imagesnumber.length; i++)
{
imagesnumber[i].style.display = "none";
}
// Wyswietlam aktualny index
$("#slide"+numer).fadeIn(500).css('display','block');
if(numer >= imagesnumber.length-1)
numer = 0;
else
numer++;
timer1 = setTimeout("changeslide()", 3000);
}
</script>
</head>
<body onload="changeslide()">
<div id="slider">
<img src="slides/img1.jpg" id="slide1">
<img src="slides/img2.jpg" id="slide2">
<img src="slides/img3.jpg" id="slide3">
<img src="slides/img4.jpg" id="slide4">
<img src="slides/img5.jpg" id="slide5">
</div>
</body>
</html>
var numer = 0;
function changeslide(){
var timeout=0;
if(numer!==0){
timeout=3000;
}
var imagesnumber=document.getElementById("slider").getElementsByTagName("img");
for(var i = 0; i < imagesnumber.length; i++)
{
imagesnumber[i].style.display = "none";
}
// Wyƛwietlam aktualny index
$("#slide"+numer).fadeIn(500).css('display','block');
if(numer >= imagesnumber.length-1)
numer = 0;
else
numer++;
timer1 = setTimeout("changeslide()", timeout);
}
PEN
function changeslide() {
if (typeof this.numer === "undefined") this.numer = 1;
var imagesnumber = document.getElementById("slider").getElementsByTagName("img");
$("#slider img").css("display", "none");
$("#slide" + numer).fadeIn(500).css('display', 'block');
if (this.numer >= imagesnumber.length)
this.numer = 1;
else
this.numer++;
timer1 = setTimeout(changeslide, 3000);
}
I moved the counter to the function so you don't mess up your variables outside.
The counter restarted too early and I replaced your for loop with a jquery solution.

Javascript - novice script not working

could someone explain why this script isn't working? I tried to figure it out for long time, but I didn't manage to do it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script>
function Xyz() {
var x = 0;
}
function Switch() {
if (x == 0) {
document.body.style.backgroundColor = "black";
x = 1;
}
else {
document.body.style.backgroundColor = "white";
x = 0;
}
}
</script>
</head>
<body>
<button type="button" onclick="Switch()">Click me</button>
</body>
</html>
if(x==0)
Since x doesn't exist, it throws a ReferenceError here and aborts the rest of the function.
You need to declare x first.
This:
function Xyz()
{
var x=0;
}
Creates a variable x that is local to the function and
Is never called anyway
You need to define variable x. I used hoisting in this example.
<!DOCTYPE html>
<html>
<head>
<script>
function Xyz()
{
var x=0;
}
function Switch()
{
if(x==0)
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
var x;
</script>
</head>
<body>
<button type="button"onclick="Switch()">Click me</button>
</body>
</html>
Issue is You need to declare a variable before using it.
function Switch()
{
if(x==0) // this x is not defined.
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
Since you need to use the same variable to update it with each click , define it outside function.
<!DOCTYPE html>
<html>
<head>
<script>
var x = 0;
function Xyz()
{
var x=0;
}
function Switch()
{
if(x==0)
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
</script>
</head>
<body>
<button type="button"onclick="Switch()">Click me</button>
</body>
</html>

Problem with putting in the right parameters

I have problem with putting in the right parameters from an eventListener into a function.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
images[0][i].addEventListener('click', function() {showImage(this)
}, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage( here is the problem ) {
var preview = document.getElementById('preview');
preview.innerhtml = image.innerhtml;
// I want to put the image into the preview element.
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams</div>
<div>trams</div>
<div>trams</div>
<div>trams</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Try this code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var images = galleryContainer.getElementsByTagName('div');
//console.log(images);
for(var i = 0; i < images.length; i++) {
images[i].addEventListener('click', showImage, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage(ev) {
ev=ev||event; // ev now point to click event object
var preview = document.getElementById('preview');
preview.innerHTML = this.innerHTML; // this point to DIV(trams)
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams1</div>
<div>trams2</div>
<div>trams3</div>
<div>trams4</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Working example http://jsfiddle.net/Cp6HJ/
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
var callback = function(item){ return function(){ showImage(item); }; }(images[0][i]);
images[0][i].addEventListener('click', callback, false);
};
};
function showImage( item ) {
var preview = document.getElementById('preview');
preview.innerHTML = item.innerHTML;
}
Use this for the function definition statement :
function showImage(image) {
...
}
And correction in the inner html statement:
(note the capitalized 'H')
preview.innerHTML = image.innerHTML;

Categories