button won't change color - javascript

I have made 30 buttons in JavaScript now I want all buttons to be green like the first button and whenever you click on a button it turns and stays red.
For some reason only the first button is green and whenever I click it it won't turn red. I tried using: button.style.backgroundColor = "red"; in a function to make the button red when clicked but this doesn't work
const color = ["green"];
page();
function onbuttonclicked() {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a < (amount + 1); a++) {
var button = document.createElement("button");
button.style.backgroundColor = color[a - 1];
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
<div id="container"></div>
EDIT
thanks for all the answers it isnt possible to only change certain buttons when you click on them right? so when i click on button1 nothing happens but whenever i click on button 3 it turn red

You need to pass nr as a parameter in onbuttonclicked function
EDIT:
OP Comment:
okay so i need to add an parameter. but i want all 30 buttons to be green so when you open the page all buttons are green this also has to do with the parameter?
For that in your loop createButton, change color[a - 1] for color[0]
const color = ["green"];
function onbuttonclicked(nr) {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
//style page
document.body.style.backgroundColor = "grey";
createButtons(30);
}
function set_onclick(amount, nr) {
for (let a = 1; a < (amount + 1); a++) {
document.getElementById(`button${a}`).setAttribute("onclick", `onbuttonclicked(${nr})`);
}
}
function createButtons(amount) {
for (let a = 1; a < (amount + 1); a++) {
const button = document.createElement("button");
button.style.backgroundColor = color[0];
button.id = `button${a}`;
button.innerHTML = `button ${a}`;
container.appendChild(button);
}
set_onclick(amount, 1);
}
page();
<div id="container"></div>

const number_of_buttons = 30;
createButtons();
function createButtons(){
var container = document.getElementById("container");
for(var i=1;i<=number_of_buttons;i++){
var button = document.createElement("button");
button.innerText = "Button " + i;
button.style.backgroundColor = "green";
button.onclick = function(event){
var source = event.target || event.srcElementl
source.style.backgroundColor = "red";
};
container.appendChild(button);
}
}
button{
margin: 10px;
font-family: 'Consolas';
font-size: 20px;
padding: 5px;
outline: none;
cursor: pointer;
transition: 0.5s;
}
button:hover{
border: 1px solid black;
}
button:active{
transform: translateY(2px);
}
<div id="container">
</div>
This is what you have asked for!
I did the styling for better looks!

This line: button.style.backgroundColor = color[a - 1]; is wrong, since your color array only contains a single string ("green"). You should do color[0], or, you need to populate the array to have 30 elements.
document.body.style.backgroundColor = color[nr - 1]; - Where is this nr variable came from? The correct line should be button.style.backgroundColor = "red"; or - again - you can populate the color (i.e const color=["green", "red"]) and use color[1].
Check out this demo

A common way to do this is to use CSS classes:
page();
function onbuttonclicked(a) {
//document.body.style.backgroundColor = color[nr - 1];
document.getElementById("button" + a).classList.remove("button")
document.getElementById("button" + a).classList.add("clickedbutton")
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<div id="container"></div>

Related

How can i make a toggle function

I am trying to make a toggle button on a website that I am making that activates a javascript navbar when pressed then when pressed a second time the navbar retracts out of sight. I have got the code working to where the navbar pops out when the button is pressed but I can't work out how to make the navbar retract.
function tog() {
var x = 0;
if (x == 0) {
document.getElementById("Sidenav").style.height = "450px";
document.getElementById("main").style.marginTop = "0px";
document.body.style.backgroundColor = "rgba(0,0,0,1)";
x = 1;
}
else {
document.getElementById("Sidenav").style.height = "0";
document.getElementById("main").style.marginTop= "0";
document.body.style.backgroundColor = "white";
x = 0;
}
};
This is the javascript that controls the toggle function, and the button is:
<div class="panel"><button class='pan' onclick='tog()'></button></div>
Any input as to where I am going wrong would be much appreciated.
Try this, the logic is: x equals 0 ? then x = 1 else x = 0.
var x = 0;
function tog() {
x = x == 0 ? 1 : 0;
if (x == 0) {
console.log(x)
} else if(x == 1){
console.log(x)
}
};
<div class="panel"><button class='pan' onclick='tog()'>Toggle!</button></div>
You could do something like this.
var x = 0;
function toggle() {
if (x === 0) {
document.getElementById("Sidenav").style.height = "150px";
document.body.style.backgroundColor = "rgba(0,0,0,1)";
x = 1;
} else {
document.getElementById("Sidenav").style.height = "0";
document.body.style.backgroundColor = "white";
x = 0;
}
};
#Sidenav {
width: 400px;
border: 1px solid #9c0000;
border-radius: 10px;
height: 0;
}
<div id="Sidenav"></div>
<button onclick="toggle()">toggle</button>
let sideNav = document.getElementById("Sidenav");
function toggle(){
sideNav.classList.toggle("open");
document.body.classList.toggle("open-bg");
}
.open{
height: 450px;
}
.open-bg{
background-color: rgba(0, 0, 0, 1);
}
make use of toggle method for classList to remove and add class alternately when button is clicked.
and try not to change css attributes too much in JavaScript. I mean it's not bad but it makes your code look kinda big.

Unable to update image position in css using javascript

There are some runner(animation-image) in my program which move from position x to y when clicked on start button, i want to add a (reverse)button on completion that when clicked on that the image moves from y to x.
Here is the link of my js-fiddle: https://jsfiddle.net/o6egL4qr/
I have added the reverse button but when clicked on that the image doesn't move at all.
class raceManager {
raceCount = 0;
races = [];
addRace() {
var mainContainer = document.getElementById('mainContainer');
mainContainer.appendChild(document.createElement('br'));
var race = new raceClass(this.raceCount);
this.races.push(race);
this.raceCount++;
}
}
class raceClass {
runners = [];
count;
runnerCount = 0;
raceDiv = document.createElement('div');
raceNum = document.createElement('div');
startRaceButton = document.createElement('input');
addRunnerButton = document.createElement('input');
revRaceButton = document.createElement('input');
tableDiv = document.createElement('div');
tableNum = document.createElement('div');
startInterval;
startTime;
revStartTime;
reverseInterval;
constructor(number) {
// store the race no.
this.count = number;
// delcare the race div id
this.raceNum.id = 'raceNum' + this.count;
// delcare the table div id
this.tableNum.id = 'tableNum' + this.count;
// Add raceDiv to the race
document.getElementById('races').appendChild(this.raceDiv);
// Add tableDiv to the race
document.getElementById('tables').appendChild(this.tableDiv);
this.applyDivProperty();
this.initializeButtons();
}
applyDivProperty() {
// apply properties to the tableNum
this.tableNum.style.display = "inline-block";
// apply properties to the raceDiv
this.raceDiv.id = "Race" + this.count;
document.getElementById(this.raceDiv.id).classList.add("raceDivClass");
this.raceDiv.appendChild(this.raceNum);
document.getElementById(this.raceNum.id).innerHTML = '<p>Race: ' + this.count + '</p>';
// append the add race button
this.raceDiv.appendChild(this.addRunnerButton);
// apply properties to the tableDiv
this.tableDiv.id = "Table" + this.count;
document.getElementById(this.tableDiv.id).classList.add("tableClass");
this.tableDiv.appendChild(this.tableNum);
document.getElementById(this.tableNum.id).innerHTML = '<p>Table: ' + this.count + '</p>';
}
initializeButtons() {
// initialize add runner button
this.addRunnerButton.type = 'Button';
this.addRunnerButton.value = 'Add Runner';
this.addRunnerButton.id = 'AddRunner' + this.count;
this.addRunnerButton.onclick = this.addRunner.bind(this);
// initialize start race buttton
this.startRaceButton.type = 'Button';
this.startRaceButton.value = 'Start Race';
this.startRaceButton.id = "startRaceButton" + this.count;
this.startRaceButton.onclick = this.startRace.bind(this);
// initialize reverse race buttton
this.revRaceButton.type = 'Button';
this.revRaceButton.value = 'Reverse Race';
this.revRaceButton.id = "revRaceButton" + this.count;
this.revRaceButton.onclick = this.revRace.bind(this);
}
addRunner() {
var track = new Runner(this); //Initialize the runner object
this.runners.push(track); //Store the runner object in runners array of Race class
if (this.runnerCount > 0) {
// append the start race button
this.raceDiv.appendChild(this.startRaceButton);
}
this.runnerCount++;
}
startRace() {
this.startTime = Date.now();
this.startInterval = setInterval(() => {
this.runners.forEach(function(element) {
element.animate();
});
document.getElementById(this.startRaceButton.id).disabled = "true";
document.getElementById(this.addRunnerButton.id).disabled = "true";
}, 50);
}
stop() {
clearInterval(this.startInterval);
// append the start race button
this.raceDiv.appendChild(this.revRaceButton);
}
revRace() {
this.revStartTime = Date.now();
this.reverseInterval = setInterval(() => {
this.runners.forEach(function(element) {
element.animateReverse();
});
document.getElementById(this.revRaceButton.id).disabled = "true";
}, 50);
}
stopRev() {
clearInterval(this.reverseInterval);
}
}
class Runner {
count = 0;
parent;
track;
sprite;
timeTaken;
trackWidth;
element;
speed;
table;
printCount = 1;
stepCount = 1;
trackNum;
tbl;
lastStep;
constructor(race) {
// initialize the divs
this.parent = race;
this.track = document.createElement('div');
this.sprite = document.createElement('div');
this.table = document.createElement('table');
// assigns #id to table and track corresponding with parent div.
this.table.id = race.tableNum.id + '_Table_' + this.parent.runnerCount;
this.track.id = race.raceNum.id + '_Track_' + this.parent.runnerCount;
this.createUI();
this.timeTaken = ((Math.random() * 5) + 3);
this.speed = this.trackWidth / (this.timeTaken * 1000);
console.log(this.trackWidth, this.timeTaken);
console.log(this.timeTaken * 100);
}
createUI() {
this.count = this.parent.runnerCount;
this.createTable();
this.createTrack();
this.createSprite();
}
createTable() {
var parentDiv1 = document.getElementById(this.parent.tableNum.id);
parentDiv1.appendChild(this.table);
this.table.setAttribute = "border"
this.table.border = "1";
document.getElementById(this.table.id).classList.add("tableClass");
this.tbl = document.getElementById(this.table.id);
this.addRow("Track " + (this.count + 1), "");
this.addRow("Time", "Distance");
}
addCell(tr, val) {
var td = document.createElement('td');
td.innerHTML = val;
tr.appendChild(td)
}
addRow(val_1, val_2) {
var tr = document.createElement('tr');
this.addCell(tr, val_1);
this.addCell(tr, val_2);
this.tbl.appendChild(tr)
}
createTrack() {
var parentDiv = document.getElementById(this.parent.raceNum.id);
parentDiv.appendChild(this.track);
this.track.appendChild(this.sprite);
document.getElementById(this.track.id).classList.add("trackClass");
this.trackWidth = this.track.getBoundingClientRect().width;
}
createSprite() {
this.sprite.id = this.track.id + "_Runner";
document.getElementById(this.sprite.id).classList.add("spriteClass");
this.element = document.getElementById(this.sprite.id);
}
animate() {
// declare time variables
var timeNow = Date.now();
var timespent = timeNow - this.parent.startTime;
var diff = Math.floor(this.timeTaken * 100);
// step is position of sprite.
var step = timespent * this.speed;
// Print table for all tracks with 10 laps.
if ((Math.round(timespent / 50) * 50) == (Math.round(((diff - 25) * this.printCount) / 50) * 50)) {
this.addRow(this.printCount + ": " + timespent, (Math.floor(step)));
this.printCount++;
}
// check condition to stop
if (step > this.trackWidth - 23) {
document.getElementById(this.parent.raceNum.id).innerHTML += 'Winner: Runner' + (this.count + 1);
this.parent.stop();
}
this.element.style.left = step + 'px';
// ------------sprite animation----------------
// start position for the image slicer
var position = (3 - (Math.floor(step / 6.5) % 4)) * 25;
// we use the ES6 template literal to insert the variable "position"
this.element.style.backgroundPosition = `${position}px 0px`;
}
animateReverse() {
// declare time variables
var timeNow = Date.now();
var timespent = timeNow - this.parent.revStartTime;
var diff = Math.floor(this.timeTaken * 100);
console.log(this.count + " position of step " + this.element.style.left);
while (this.stepCount < 2) {
this.lastStep = parseFloat(this.element.style.left);
this.stepCount++;
}
console.log(this.count + " this is lastStep " + this.lastStep);
// step is position of sprite.
var step = this.lastStep - (this.speed * timespent);
// Print table for all tracks with 10 laps.
if ((Math.round(timespent / 50) * 50) == (Math.round(((diff - 25) * this.printCount) / 50) * 50)) {
this.addRow(this.printCount + ": " + timespent, (Math.floor(step)));
this.printCount++;
}
// check condition to stop
if (step < 25) {
document.getElementById(this.parent.raceNum.id).innerHTML += 'Winner: Runner' + (this.count + 1);
this.parent.stopRev();
}
this.element.style.left = step + 'px';
// ------------sprite animation----------------
// start position for the image slicer
//var position = (3 - (Math.floor(step / 6.5) % 4)) * 25;
//this.element.style.backgroundPosition = position + 'px 0px';
}
}
manager = new raceManager();
#tableContainer {
float: left;
}
#addRaces {
text-align: center;
}
.raceDivClass {
margin: 1% auto;
width: 60%;
text-align: center;
border: 1px solid;
}
.tableClass {
text-align: center;
border: 1px solid;
margin: 5px;
float: left;
}
.trackClass {
background-color: black;
height: 30px;
width: 98%;
margin: 1%;
position: relative;
}
.spriteClass {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGgAAAAeCAYAAADAZ1t9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAASwSURBVGhD7Zq/axRBFMfv9u4MxATUSgsVm3QWigYbexuxUkiaKIqNoIUiwRSJoJLCxpSCaJoEYimo/4AgQVRIZxdBEIREYwzc5X74vndvlrm5mdnZ3dm9oPnAsDubu52Z93373pvNFQsJOXO9NUKHsU4vZPH90+IXPt/FA2kEmqbDTKcX8pza7K5I/vAtEJghge7zeSrwlDYbtYlmfWuILxWC8uBmUNoz/784wY4WaPRq9SGJcY+7Mt7GEOzUkB0pkGHi4Ci1K53TEK8h7tTE+pPywL6b3JXJQqBcQ7arQwR87AE34ElPUsPE1ZapODsErFHnnD7AfVWb9oylFYjVFcKoQuQC5kD55hB3Qxrbf17RYbHT+/fpCXGSOEmEaYcevofwhkRxXM0/VCi8azXr3+q1Xw8+LRxZ4cte4PneoHaQ2iVck0gVThVbyOhSRM9YOoFMyR9eW6KmLkAGYW6Vmjx47AViUfSkPC5V9p7nS23q1Z9zH+b33+KuF9iAOocUa0lcKFjubQJ2h51D5zbmIAVM9gc1mzgAE0kdFlFaq+JkQYQBV+FYOYoDGy9Tw3dgQ7QxnUBQUHxAtJfUhqllDhbWam4f525mJDCgMynufZFa13d6BILHsOeEjS6PUjMNtsRHFXgExI2V0PN6egiEkTzFMdlJgM/3zMd1H2Tzhjlqa53TLhLFbsvep9Cob70uFsuffbxJoHWZcq1A5CCZyDUZ7gtxotKDCsafdRHIZSFe9j9wBl1xoIJSuxhUVpIK5eB0JiILHo29EouDtVmLBF4IKjIbWOQkfzYVruENn+ESXFe+upBJeDMQVfWiyXQ5fFQV57oQLyLJL0VlsAfi06yJyhMuIOci7Efdqy0ENzxxonVFI22IY0NDHN1mykaX+nHAmKbw1qhtLLVaze8U1o6Jv9OmdaEYlI1lsLQGGVGwmMKbKZ8KXHIQxnUJn062CgVSFmQTRjySpr8n2nlb3lxTztl8W6+u3x0YOlylrpij1Vi0Hl3uxNx/U9MWIYSPtwZxclukSG2B4qreOTV+3skzBBgbuafVrJ0sVYbO8eUe4r5FMAgEbEnbSSC2l/p0grgRB1jHDGKqjt019kkwvoid4okS4D7O+Qji4MmxiQMonI2cGP/qYwMbt6LSAXFEzpCbyYaJcxuKBAwWJQ5EwATCTScLBeUhVGKRTIWBCgQsVYavcdcF8UZEnVveYPwXfIwNBMJCdF/GNeEZCFnahMzX1A0dgEi6MJALigP1SyiMCdu9wZH7sZBzkGpM5zcBljAZGdNPX964UAhKt0vlwbN8SQs2p/Xq2lTSfzU4hvK0OUily4b0PV1etI4Z+SbBFYMBrIPjO1QuT1N+GedLbVC1FYM9Hyk31fgScHYYE5JhD1Dz/r+fKPoqEJAMILAa1VRaU+HwaPnZwBR3vWJwJCDCUSonsKERKHJMrwLFAYbSbUwRyujanawMZfBikPXTEzvCgKhXPZmhe+/W2ZCuTWXpxQbgyWGFmhGILLb8p6V/AmnKa+Qd3783cCDz0JaGvgmEX4jyaRu8W6N8NM/dPGlvvvk8T5ye2r7mIIQ5PEl5/pyXc4FzIeOLZOMWCn8Bh1eBvOSZzIIAAAAASUVORK5CYII=');
position: absolute;
height: 30px;
width: 25px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="mainContainer">
<div id="addRaces">
<input type="Button" value="Add Race" onclick="manager.addRace()">
</div>
<div id="races">
</div>
<br>
</div>
<div id="tableContainer">
<div id="tables"></div>
</div>
</body>
</html>
I expect it to move from y to x after clicking the reverse button, but it is not moving.
When you run the reverse function the elements are no longer referencing the dom elements.
I am actually not sure why that is, maybe someone else can chime in.
Anyway, this will fix your problem:
Replace this.element.style.left = step + 'px';
With: document.getElementById(this.element.id).style.left = step + 'px';

How can i remove an event listener from multiple elements in JavaScript?

I'm working on a card game where the user has to select a card from a set of 4. If it is an Ace then they win if not then they lose. But I'm having some trouble removing the event listener of click from the set of cards after the first card has been clicked.
for(var i = 0; i < card.length; i++)
{
card[i].addEventListener("click",display);
}
function display()
{
this.setAttribute("src","CardImages/" + deck[this.id] + ".jpg");
this.setAttribute("class","highlight");
if(firstGo == 0)
{
firstGo++;
firstCard = this;
this.removeEventListener("click",display);
console.log("card" + deck[this.id]);
}
else
{
alert("You've already selected a card");
this.removeEventListener("click",display);
}
}
You are adding click events using a loop because you have multiple cards.
for(var i = 0; i < card.length; i++) {
card[i].addEventListener("click", display);
}
but you're removing the event listeners using
this.removeEventListener("click",display);
which will only remove the listener on the card you clicked. If you want to remove the listener on other cards too, you should also remove them in a loop.
function display() {
this.setAttribute("src","CardImages/" + deck[this.id] + ".jpg");
this.setAttribute("class","highlight");
if (firstGo == 0) {
firstGo++;
firstCard = this;
// this.removeEventListener("click",display);
for (var i = 0; i < card.length; i++) {
card[i].removeEventListener("click", display);
}
console.log("card" + deck[this.id]);
} else {
alert("You've already selected a card");
// this.removeEventListener("click",display);
for (var i = 0; i < card.length; i++) {
card[i].removeEventListener("click", display);
}
}
}
Here's a working demo.
var cards = document.getElementsByClassName("card");
for (var i = 0; i < cards.length; i++) {
cards[i].addEventListener("click", display);
}
function display() {
this.classList.add("highlight");
for (var i = 0; i < cards.length; i++) {
cards[i].removeEventListener("click", display);
}
}
.card {
float: left;
padding: 50px 40px;
border: 1px solid rgba(0,0,0,.2);
margin: 5px;
background: white;
}
.card:hover {
border: 1px solid rgba(0,0,255,.4);
}
.card.highlight {
border: 1px solid rgba(0,200,0,.5);
}
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
I'm not sure what your card array looks like, but I filled in the rest on a codepen and it seems to be successfully removing the eventListener. Is your card array referencing specific DOM elements like this for example?
var a = document.getElementById('A');
var b = document.getElementById('B');
var c = document.getElementById('C');
var card = [a, b, c];

eventlistener javascript problems

I'm trying to learn Javascript and at the moment and I am working on AddEventListener.
What I'm trying to do is to add a new row and so far it works.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.colorOrange {
background-color: orange;
}
.colorBlue {
background-color: blue;
}
.colorYellow {
background-color: yellow;
}
.colorGray {
background-color: gray;
}
.colorRed {
background-color: red;
}
.colorGreen {
background-color: green;
}
.colorWhite {
background-color: white;
}
#main {
margin: 0 auto;
width: 325px;
text-align: center;
background-color: gray;
}
.row {
width: 300px;
padding: 10px;
border: 1px solid black;
display: block;
}
.hideButton, .mainText, .deleteButton {
margin: 0 auto;
padding: 10px;
border: 1px solid black;
display: inline;
}
.btn {
}
</style>
</head>
<body>
<div id="main">
<div class="AddBtn btn">Add</div>
<input type="text" id="txtBox" name="text till ruta" />
</div>
<script>
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
So far everything works as I want it to do. But when I click on "<" it will go in to this function and find all tags with the hideButton class in it.
The first click it won't find anything, but the second time it will find the "<" value and an alert window will popup and show the value. Here is where I
get lost and can't get it to work. When you click the the third time it will
loop or whatever to call it - anyway it will show the alert window 2 times and
then if you repeat the same click it will do the same thing 3 times and so it goes.
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
for (var j = 0; j < hideButton.length; j++) {
hideBtn = hideButton[j];
hideBtn.addEventListener('click', function () {
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}, false);
}
}
}, false);
}
}
window.onload = addListeners;
</script>
</body>
</html>
The goal with this exercise is that
when you click add button add the text from the input field and add that text to the new row.
and "<" shall hide the row and change it to ">" to show it again
and "X" shall just delete the row.
But what I need help with is finding the value part that I mentioned above.
Here is my rework of your javascript. I explained my solution in your comment, but it may be a bit more clear if illustrated.
In the addListeners function, I removed the hideOrShow call as it shouldn't be called in the add button.
Next, I removed the for loop in the hideOrShow method as you really are only after the caller. I also removed the addEventListener call in the same method as you already have an event listener on that element, so there's no need to add one again.
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
//hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}
}, false);
}
}
window.onload = addListeners;

javascript change color after each event

I have three elements, the first element clicked needs to change, lets say to red. no matter what element is clicked. The second element clicked needs to turn green then last element clicked needs to turn blue. When these elements are clicked a second time they need to turn back to white.
The first element is not a problem but how do I move on to change the other elements?
css
.container {
background-color: #ffffff;
border: 1px solid blue;
border-radius: 10px;
width: 100px;
height: 50px;
}
.red { background-color: #ff0000; }
.green { background-color: #00ff00; }
.blue { background-color: #0000ff; }
html
<div class='container' id='1' onclick='changeColor(1);'></div>
<div class='container' id='2' onclick='changeColor(2);'></div>
<div class='container' id='3' onclick='changeColor(3);'></div>
javascript
function changeColor(whichOne)
{
var element = document.getElementById(whichOne);
if ( whichOne == 1 || whichOne == 2 || whichOne == 3 )
{
element.classList.toggle("red");
}
}//end
The general process for something like this is:
Use an Array to hold the values you want to cycle through and a counter to indicate the position of the next value to use.
When you need to apply a value, pull it from the Array using the counter as the index.
After using a value, increment the counter so it indicates the next value in the Array. If the counter has reached the end of the Array, reset it back to 0.
Here is an example:
var valuesToUse = ['classA', 'classB', 'classC'],
nextIndex = 0;
function applyValue(target) {
var value = valuesToUse[nextIndex];
nextIndex = (nextIndex + 1) % valuesToUse.length;
// use `value` on `target`
}
Here is this idea applied to your problem via either cycling through classnames or through color values in JavaScript.
http://jsfiddle.net/teTTR/1/
var colors = ['#ff0000', '#00ff00', '#0000ff'],
nextColor = 0;
var classes = ['red', 'green', 'blue'],
nextClass = 0;
var elms = document.querySelectorAll('.color-changer'),
len = elms.length,
i = 0;
for (; i < len; i++) {
elms[i].addEventListener('click', changeColor);
}
elms = document.querySelectorAll('.class-changer');
len = elms.length;
i = 0;
for (; i < len; i++) {
elms[i].addEventListener('click', changeClass);
}
function changeClass(event) {
var elm = event.currentTarget,
currentClass = hasClass(elm, classes);
if (currentClass) {
elm.classList.remove(currentClass);
} else {
elm.classList.add(classes[nextClass]);
nextClass = (nextClass + 1) % classes.length;
}
}
function changeColor(event) {
var element = event.currentTarget;
if (element.style.backgroundColor) {
element.style.backgroundColor = '';
} else {
element.style.backgroundColor = colors[nextColor];
nextColor = (nextColor + 1) % colors.length;
}
}
function hasClass(elm, classes) {
var len,
i;
if (isArray(classes)) {
len = classes.length;
i = 0;
for (; i < len; i++) {
if (elm.classList.contains(classes[i])) {
return classes[i];
}
}
return false;
}
return elm.classList.contains(classes) ? classes : false;
}
function isArray(item) {
return Object.prototype.toString.call(item) === '[object Array]';
}

Categories

Resources