how to activated new function after button clicked for three times - javascript

i want to add new function after i clicked the button 3 times and erase/remove the former function
html file:
<body>
<div id="background">
<p>this background white, before</p>
</div>
<button class="btn-1">change color</button>
</body>
javascript:
const btn1 = document.querySelector(".btn-1") ;
const bg = document.getElementById("background")
const toRed = ()=>{
bg.style.backgroundColor = "red";
}
const toBlue = ()=>{
bg.style.backgroundColor = "steelblue";
}
btn1.addEventListener('click', toRed);
// i want this btn1 have function to clear function toRed and add toBlue instead after clicked 3 times

remove the event listener and add a new one when it was clicked three times:
const btn1 = document.querySelector(".btn-1");
const bg = document.getElementById("background");
var redClicked = 0;
const toRed = ()=>{
bg.style.backgroundColor = "red";
redClicked++;
if (redClicked >= 3) {
btn1.removeEventListener('click', toRed);
btn1.addEventListener('click', toBlue);
}
}
const toBlue = ()=>{
bg.style.backgroundColor = "steelblue";
}
btn1.addEventListener('click', toRed);
<body>
<div id="background">
<p>this background white, before</p>
</div>
<button class="btn-1">change color</button>
</body>

Related

Repetition of two variables one after the other in Math.random()

I wrote the following code to randomly change the background color, but sometimes the two colors are repeated one after the other .... How do you think I can write the code so that the two colors are not repeated one after the other?
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
btn.addEventListener("click", function() {
const randomNumber = getRandomNumber()
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber]
})
function getRandomNumber() {
return Math.floor(Math.random() * colors.length)
}
<h2>background color : <span class="color">#f1f5f8</span></h2>
<button class="btn btn-hero" id="btn">click me</button>
This will happen because since it is completely random you might get the same number again.
You can put a while loop to ensure you are getting a new color every time. Keep a loop that keeps on running unless you get a new number.
Here prevNumber is used to keep track of the previous number. Now the code keeps on generating a new number until you have a different number from the previous one.
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
let prevNumber = 0;
btn.addEventListener("click", function() {
let randomNumber = getRandomNumber();
while(randomNumber == prevNumber){
randomNumber = getRandomNumber();
}
prevNumber = randomNumber;
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber]
})
function getRandomNumber() {
return Math.floor(Math.random() * colors.length)
}
<h2>background color : <span class="color">#f1f5f8</span></h2>
<button class="btn btn-hero" id="btn">click me</button>
You could save the last number generated. If that number comes back again, get another one.
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
let last = -1
btn.addEventListener("click", function() {
let randomNumber = getRandomIndex()
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber]
})
function getRandomIndex() {
let randomIndex = Math.floor(Math.random() * colors.length)
if (randomIndex === last) {
return randomIndex = getRandomIndex()
} else {
last = randomIndex
return randomIndex
}
}
<h2>background color : <span class="color">#f1f5f8</span></h2>
<button class="btn btn-hero" id="btn">click me</button>
Both current answers are totally ok. If you want to randomize just once you can do:
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
let currentColor = colors.pop();
btn.addEventListener("click", function() {
const randomNumber = getRandomNumber()
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber]
})
function getRandomNumber() {
const chosen = Math.floor(Math.random() * colors.length)
const newColor = colors[chosen];
colors.splice(chosen,1,currentColor);
currentColor = newColor;
return chosen;
}
<h2>background color : <span class="color">#f1f5f8</span></h2>
<button class="btn btn-hero" id="btn">click me</button>
This way you prevent the current colour to be selected, and once the randomization has been done, you insert the one left out while removing the newly selected
write closure like noConsecutiveRandom to get random number but not consecutively repeat.
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
function noConsecutiveRandom(size) {
let last;
return function rand() {
const cur = Math.floor(Math.random() * size);
return cur === last ? rand() : (last = cur);
};
}
const getRandomNumber = noConsecutiveRandom(colors.length);
btn.addEventListener("click", function() {
const randomNumber = getRandomNumber()
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber]
})
<h2>background color : <span class="color">#f1f5f8</span></h2>
<button class="btn btn-hero" id="btn">click me</button>

i don't now how use background from js

I am a newbie to js and I would like to know how you can use background from javascript let's say I can set the color of a button by doing this:
const btnPulsado = (e) =>{
const btn= e.target;
btn.style.backgroundColor= 'red';
can I do it somehow with backgroundImage?
You can use
e.target.style.backgroundColor = __ANY_COLOR_CODE;
function genRanHex(size) {
return [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('')
}
const btn = document.querySelector("button");
btn.addEventListener("click", e => {
e.target.style.backgroundColor = `#${genRanHex(6)}`;
})
<button> click me to change color </button>

Button that assigns different color to text in javascript

I am new to javascript. I have a problem but I don't know what it could be. Iam supposed to link my javascript to my html. There are three buttons that should turn the text to a diffrent color on clicking. But it is not working.
// this is the red button
const header = document.querySelector("#header");
const clicker = document.querySelector(".clicker-red");
clicker.addEventListener("click", () => {
header.style.backgroundColor = "red";
header.classList.add("large");
});
// this is the green button
const clicker = document.querySelector(".clicker-green");
clicker.addEventListener("click", () => {
header.style.backgroundColor = "green";
header.classList.add("large");
});
// this is the purple button
const clicker = document.querySelector(".clicker-pruple");
clicker.addEventListener("click", () => {
header.style.backgroundColor = "purple";
header.classList.add("large");
});
As I have said in the comments, You cannot declare variable with same name in the same Lexical Environment (i.e, in the same block).
So, you need to change the variable name.
Here is the working example.
const header = document.querySelector("#header");
const clickerRed = document.querySelector(".clicker-red");
clickerRed.addEventListener("click", () => {
header.style.backgroundColor = "red";
});
// //this is the green button
const clickerGreen = document.querySelector(".clicker-green");
clickerGreen.addEventListener("click", () => {
header.style.backgroundColor = "green";
});
// // this is the purple button
const clickerPurple = document.querySelector(".clicker-purple");
clickerPurple.addEventListener("click", () => {
header.style.backgroundColor = "purple";
});
<div id="header">
Header</div>
<button class="clicker-red" type="button">Red</button>
<button class="clicker-green" type="button">Green</button>
<button class="clicker-purple" type="button">Purple</button>

How can i make a HTML button run three functions one after another

My code has three functions. I want one button to run function one when pressed the first time then function 2 when pressed the second time function 3 when pressed the third time and then for it to reset.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green]
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
</script>
</head>
<body>
<button id="sequence" onclick="changeyellow" onclick="changered" onclick="changegreen">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>
You can use only one function and a global variable that contains the current color like this :
<!DOCTYPE html>
<html>
<head>
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green];
var currentColor = 0;
function changeColor() {
var img = document.getElementById("light");
img.src= lights[currentColor];
if (currentColor === (lights.length - 1)) {
currentColor = 0;
} else {
currentColor++;
}
return false;
}
</script>
</head>
<body>
<button id="sequence" onclick="changeColor();">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>
There are several ways you could handle it, but here's an easy one:
above:
function changered()
add this:
var cur_button = 1
Then change your button to this:
<button id="sequence" onclick="handle_click()">sequence</button>
and add this function:
function handle_click()
{
if(cur_button == 1)
{
cur_button = 2
changered()
}
else if(cur_button == 2)
{
cur_button = 3
changeyellow()
}
else if(cur_button == 3)
{
cur_button = 1
changegreen()
}
}
There you go
<input type="button" name="btnn" onclick="runFunction()" />
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png";
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png";
var green = "https://s29.postimg.org/5ljr1ha3r/green.png";
var lights =[red,yellow,green];
var a =1;
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
function runFunction()
{
if(a==1)
{
changered();
a++;
}
if(a==2)
{
changeyellow();
a++;
}
if(a==3)
{
changegreen();
a=1;
}
}
I can use the switch statement, and simply reference the lights array to determine which to display next. Seems pretty painless.
var red = "https://snowmonkey.000webhostapp.com/images/red.png"
var yellow = "https://snowmonkey.000webhostapp.com/images/yellow.png"
var green = "https://snowmonkey.000webhostapp.com/images/green.png"
var lights =[red,yellow,green]
handleClick = function(){
var light = document.getElementById("light");
switch (light.src) {
case lights[0]:
light.src = lights[1];
break;
case lights[1]:
light.src = lights[2];
break;
case lights[2]:
light.src = lights[0];
break;
}
}
#light {
float: right;
width: 50px;
}
<button id="sequence" onclick="handleClick();">sequence</button>
<br><br><br>
<img id="light" src="https://snowmonkey.000webhostapp.com/images/green.png" />
https://jsfiddle.net/x1rqwzvy/1/
You shouldn't add more than one onclick in your html code. If you do the handlers will activate simultaneously. This means you have to handle the change with JavaScript.
To determine the light you would simply increment a value in the following example:
function lightChange() {
lightChange.incrementer = lightChange.incrementer || 1;
switch (lightChange.incrementer) {
case 1:
changered();
break;
case 2:
changeyellow();
break;
case 3:
changegreen();
lightChange.incrementer = 0;
break;
}
lightChange.incrementer++;
function changered() {
var img = document.getElementById("light");
img.src = lights[0];
return false;
}
function changeyellow() {
var img = document.getElementById("light");
img.src = lights[1];
return false;
}
function changegreen() {
var img = document.getElementById("light");
img.src = lights[2];
return false;
}
}
then just change the onclick handler to lightChange instead of trying to add three consecutive handlers.
<button id="sequence" onclick="lightChange()">sequence</button>
how about
var counter = 0;
function changeColor(){
counter++;
var img = document.getElementById("light");
img.src= lights[counter % 3];
return false;
}
and your html should be:
<button id="sequence" onclick="changeColor()">sequence</button>
You can create a function array and then remove entries from it once done.
var functionArray = [changered,changeyellow,changegreen]
function sequenceClick(){
functionArray[0]();
functionArray.shift();
}
Complete Code:
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green]
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
var functionArray = [changered,changeyellow,changegreen]
function sequenceClick(){
functionArray[0]();
functionArray.shift();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="sequence" onclick="sequenceClick()">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>

Changing picture frame with toggle button

Ok so we have a simple user info editing page.I want to create a toggle button which swaps profile picture border-radius from 0 to 25 and backwards.But the 2nd part doesnt work.I created if to check if the boarder radius is 25 already so it will make it 0, but it does not work.Here is my code
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="changeImage()">NextImage</button>
<button onclick="changeShape()">ChangeShape</button>
<button onclick="uploadImage()">Upload Image</button>
</body>
<script>
var images = [ 'profile1.png', 'profile2.png','profile3.png'];
var index = 0;
var array_length = 3;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage(){
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % array_length;
img.src = images[index];
}
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "25px";
if(shape.style.borderRadius == 25){
var shape2 = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "0px";
}
}
function uploadImage() {
images.push("profile4.png");
array_length++;
}
</script>
</html>
Any ideas why it doesnt work?
You are uselessly assigning variables in your function by the looks of it.
There is no need to declare shape2. Just declare shape once and then use that to check. Also make sure to check shape.style.borderRadius against a string like "25px" as that will be returned.
Try something like this:
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0];
if(shape.style.borderRadius == "25px"){
shape.style.borderRadius = "0px";
}else{
shape.style.borderRadius = "25px";
}
}

Categories