Button changing newest div item instead of the correct - javascript

I created a div table of sorts, where there is a button, and that button creates a box, and what is supposed to happen is that you can click any of the {x} boxes and it colors it black However, instead of coloring that box black(or white), it colors the newest one black(or white). How do I change this?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Rule 110</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
<center><h1>Rule 110</h1></center>
<div class="grid-container">
<main id="content"></main>
</div>
<button onclick=add() class="button">+</button>
</body>
</html>
Javascript:
const first = document.getElementById("first")
const second = document.getElementById("second")
const third = document.getElementById("third")
const fourth = document.getElementById("fourth")
const fifth = document.getElementById("fifth")
const sixth = document.getElementById("sixth")
const seventh = document.getElementById("seventh")
const eigth = document.getElementById("eigth")
const ninth = document.getElementById("ninth")
var extra = 1;
var thingrowx=0;
var thingrowy = 1;
function changeColor(test) {
if (document.getElementById(test).className === "grid-item-white"){
document.getElementById(test).className="grid-item-black";}
else {
document.getElementById(test).className="grid-item-white";
}
}
function createTable() {
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
for(var r=0;r<parseInt(rn,10);r++)
{
var x=document.getElementById('myTable').insertRow(r);
for(var c=0;c<parseInt(cn,10);c++)
{
var y= x.insertCell(c);
y.innerHTML="Row-"+r+" Column-"+c;
}
}
}
function repeat(func, times) {
func;
times && --times && repeat(func, times);
}
function test() {
document.querySelector('#content').insertAdjacentHTML(
'afterbegin',
`<div class="grid-item-white" id="combined" onclick=changeColor('combined')>
</div>`
)
}
function add() {
extra += 1;
thingrowx += 1;
var combined = "(" + thingrowx + "," + thingrowy + ")"
alert(combined)
repeat(test(), thingrowy)
}
CSS:
.button {
border: none;
background-color: black;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
color: white;
}
.button1 {
background-color: white;
color: black;
border: 2px solid #4CAF50;
}
.button1:hover {
background-color: #4CAF50;
color: white;
}
.button2 {
background-color: white;
color: black;
border: 2px solid #008CBA;
}
.button2:hover {
background-color: #008CBA;
color: white;
}
.grid-container {
display: grid;
grid-template-columns: 50px 50px 50px 50px 0px 50px 50px 50px 0px 50px 50px 50px 50px 50px 50px 50px;
padding: 10px;
}
.grid-item-white {
background-color: white;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
.grid-item-black {
background-color: black;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
color: white
}
body {background-color: #cdf1eb ;}

I think the problem is in the test function.
function test() {
document.querySelector('#content').insertAdjacentHTML(
'afterbegin',
`<div class="grid-item-white" id="combined" onclick=changeColor('combined')>
</div>`
)
}
You're setting the id to "combined" for every new added element. But an id must be unique for each element in the whole html document. May be you intended to do the following.
function test(combined) {
// use the combined index that is passed from the add function
document.querySelector('#content').insertAdjacentHTML(
'afterbegin',
// -------------------------------vvvvvvvvvvv-- use template literal
`<div class="grid-item-white" id="${combined}" onclick=changeColor('${combined}')>
</div>`
)
}
function add() {
extra += 1;
thingrowx += 1;
var combined = "(" + thingrowx + "," + thingrowy + ")"
alert(combined)
repeat(test(combined), thingrowy) // pass the combined index to the test method
}
Your code is very cluttered with poor naming and lots of unused variables and functions, so I've tried to refactor a little!
const contentElement = document.getElementById("content");
contentElement.addEventListener("click", (event) => {
// here event.target represents the element that has been clicked on
changeColor(event.target);
});
let rowX = 0;
let rowY = 1;
function changeColor(element) {
if (element.className === "grid-item-white")
element.className = "grid-item-black";
else element.className = "grid-item-white";
}
function add() {
rowX += 1;
const combined = "(" + rowX + "," + rowY + ")";
// alert(combined);
document
.querySelector("#content")
.insertAdjacentHTML(
"afterbegin",
`<div class="grid-item-white" data-id="${combined}"></div>`
);
}
.button {
border: none;
background-color: black;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
color: white;
}
.button1 {
background-color: white;
color: black;
border: 2px solid #4caf50;
}
.button1:hover {
background-color: #4caf50;
color: white;
}
.button2 {
background-color: white;
color: black;
border: 2px solid #008cba;
}
.button2:hover {
background-color: #008cba;
color: white;
}
.grid-container {
display: grid;
grid-template-columns: 50px 50px 50px 50px 0px 50px 50px 50px 0px 50px 50px 50px 50px 50px 50px 50px;
padding: 10px;
}
.grid-item-white {
background-color: white;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
.grid-item-black {
background-color: black;
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
color: white;
}
body {
background-color: #cdf1eb;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Rule 110</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center>
<h1>Rule 110</h1>
</center>
<button onclick="add()" class="button">+</button>
<div class="grid-container">
<main id="content"></main>
</div>
<script src="script.js"></script>
</body>
</html>
Here I've used event delegation to listen on click event on any grid items. So if we listen for click events on the #content element and use the event.target then we get the grid item that has been clicked on. Then we can pass that element to the changeColor method.
If you don't understand anything feel free to ask me in the comment. Hope this helps.

I think it's because all of your divs has the same id ("combined"), so the browser get the top one in the DOM. This can be solved if you give each of them a unique id. This works for me:
`<div class="grid-item-white" id="combined${extra}" onclick=changeColor('combined${extra}')`

Related

Javascript - How do I change attribute of each generated textbox?

I Am currently working on a small project but tried everything and can't come up with a solution to my problem. I'm working on a to do list and using javascript to generate textboxes with a button that stores its value. The Button generates a textbox and 3 additional buttons (1 delete task button (red), 1 change its value button (yellow) and 1 completed button (green) which moves the task to a new list and generates 2 additional buttons delete task and the yellow button which does the same as preview). The problem is that when generating x amount of textboxes only the first textbox will work when changing its value (clicking on yellow button), how can I make it so each button works individually for respective textbox.
The same problem remains when clicking on the green button (completed button) in which only the first textbox in the list will display its value.
const syssla = document.querySelector("#min-syssla");
let firstbutton = document.querySelector(".firstbutton");
const ullist = document.querySelector(".unorderedlist");
const listdone = document.querySelector(".list-done");
firstbutton.addEventListener("click", task);
function task(event) {
const tododiv = document.createElement("div");
tododiv.classList.add("todo");
const list = document.createElement('li');
list.classList.add('todo-item');
tododiv.appendChild(list);
const completedButton = document.createElement('button');
completedButton.innerText = "Färdig";
completedButton.classList.add("complete_btn");
list.appendChild(completedButton);
const editButton = document.createElement('button');
editButton.innerText = "Ändra";
editButton.classList.add("edit_btn");
list.appendChild(editButton);
const eraseButton = document.createElement('button');
eraseButton.innerText = "Radera";
eraseButton.classList.add("erase_btn");
list.appendChild(eraseButton);
var textinput = document.createElement("input");
textinput.type = "text";
textinput.setAttribute('disabled', 'disabled');
textinput.classList.add("newbox");
list.appendChild(textinput);
textinput.value = syssla.value;
ullist.appendChild(tododiv);
firstbutton.value = "";
event.preventDefault();
}
ullist.addEventListener('click', deletecheckbox);
function deletecheckbox(e) {
let item = e.target;
if (item.classList[0] === 'erase_btn') {
const make = item.parentElement;
make.remove();
}
if (item.classList[0] === 'complete_btn') {
const radera1 = item.parentElement;
let completedButton = document.querySelector(".complete_btn");
const tododiv2 = document.createElement("div");
tododiv2.classList.add("todo2");
const list2 = document.createElement('li');
list2.classList.add('todo-item2');
tododiv2.appendChild(list2);
const editButton1 = document.createElement('button');
editButton1.innerText = "Ändra";
editButton1.classList.add("edit_btn1");
list2.appendChild(editButton1);
const eraseButton1 = document.createElement('button');
eraseButton1.innerText = "Radera";
eraseButton1.classList.add("erase_btn1");
list2.appendChild(eraseButton1);
let textinput2 = document.createElement("input");
textinput2.type = "text";
textinput2.setAttribute('disabled', 'disabled');
textinput2.classList.add("newbox2");
list2.appendChild(textinput2);
listdone.appendChild(tododiv2);
textinput = document.querySelector(".newbox");
textinput2.value = textinput.value;
radera1.remove();
}
editButton = document.querySelector(".edit_btn");
editButton.addEventListener('click', change());
function change() {
textinput = document.querySelector(".newbox");
if (item.classList[0] === "edit_btn") {
if (textinput.disabled === true) {
textinput.removeAttribute('disabled', 'disabled');
} else if (textinput.disabled === false) {
textinput.setAttribute('disabled', 'disabled');
}
}
}
}
listdone.addEventListener('click', donebox);
function donebox(ev) {
let item1 = ev.target;
if (item1.classList[0] === 'erase_btn1') {
const eraser = item1.parentElement;
eraser.remove();
}
if (item1.classList[0] === 'edit_btn1') {
textinput2 = document.querySelector(".newbox2");
if (textinput2.disabled === true) {
textinput2.removeAttribute('disabled', 'disabled');
} else if (textinput2.disabled === false) {
textinput2.setAttribute('disabled', 'disabled');
}
}
}
body {
margin: 0;
padding: 0;
background-size: cover;
}
h1 {
text-align: center;
font-size: 60px;
margin: 0 auto;
padding: 25px;
-webkit-text-stroke: 1.5px white;
background-color: rgb(48, 49, 51, 0.7);
opacity: 1;
}
#min-syssla {
position: relative;
left: 70px;
top: 50px;
border: 2px solid blue;
height: 25px;
width: 170px;
}
#wrapper-box {
border: 1px black;
position: relative;
top: 35px;
display: block;
width: 450px;
height: 700px;
background-image: linear-gradient(180deg, lightblue, blue 90%);
border: 3px outset blue;
border-top-left-radius: 5%;
border-top-right-radius: 5%;
z-index: 1;
padding: 10px;
margin-left: 37.5%;
margin-right: 40%;
}
.firstbutton {
position: relative;
left: 270px;
bottom: 18px;
border: 1px ridge blue;
border-radius: 5px;
padding: 3px;
width: 80px;
height: 30px;
}
h2 {
margin: 30px;
}
.todo-item {
margin-top: 20px;
}
.complete_btn {
margin-left: 20px;
float: right;
padding: 6px;
color: white;
border: 1.5px solid black;
background-color: green;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.complete_btn:hover {
background-color: rgb(86, 234, 7, 0.9);
}
.erase_btn {
float: right;
margin-left: 22px;
padding: 6px;
color: white;
border: 1.5px solid black;
background-color: red;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.erase_btn:hover {
background-color: rgb(255, 84, 84, 0.9);
}
.edit_btn {
float: right;
margin-left: 20px;
padding: 6px;
color: black;
border: 1.5px solid black;
background-color: yellow;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.edit_btn:hover {
background-color: rgb(213, 219, 46, 0.9);
}
.newbox {
border-radius: 5px;
border: 2px ridge darkorange;
padding: 5px;
}
.erase_btn1 {
float: right;
margin-right: 25px;
padding: 6px;
color: white;
border: 1.5px solid black;
background-color: red;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.erase_btn1:hover {
background-color: rgb(255, 84, 84, 0.9);
}
.edit_btn1 {
margin-right: 75px;
float: right;
padding: 6px;
color: black;
border: 1.5px solid black;
background-color: yellow;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.edit_btn1:hover {
background-color: rgb(213, 219, 46, 0.9);
}
.newbox2 {
border-radius: 5px;
padding: 5px;
border: 2px ridge greenyellow;
}
.todo-item2 {
margin-top: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Kunskapskontroll</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel=stylesheet href="css/style.css">
</head>
<body>
<h1>Mina Sysslor</h1>
<div id="wrapper-box">
<input type="text" id="min-syssla" placeholder="Min syssla" name="min-syssla"><br><br><br>
<button class="firstbutton" type="submit">Lägg till</button>
<div class="syssla-container">
<h2>Att göra</h2>
<ul class="unorderedlist"></ul>
<h2>Färdiga</h2>
<ul class="list-done"></ul>
</div>
I haven't tried much because I have no clue of how to manage to change the attribute for every new textbox.

Why won't these for loops work? To-Do list app [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Event binding on dynamically created elements?
(23 answers)
Closed last year.
I can't figure out why the for loops won't iterate. I had them working at one point inside of the printInput function, but not outside. BTW, I'm still working on the code portion of the for both loops. One is supposed to close the object by removing it. The other is supposed to make the html element editable.
// close button
var closes = document.getElementsByClassName("closes");
for (var i = 0; i < closes.length; i++){
closes[i].onclick = function (){
var l = closes[i];
l.remove();
}
}
// edit button
var edit = document.getElementsByClassName("edit");
for(var i = 0; i < edit.length; i++){
edit[i].onclick = function (){
var x = this.parentElement;
x.contentEditable = true;
}
}
// Submits input by hitting enter
document.addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
printInput();
}
});
// Toggles checked class for finished chores
let selection = document.querySelector('ul');
selection.addEventListener("click", function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
// This creates a new list object.
function printInput() {
let input = document.getElementById('todotext').value;
if (input === "" || null){
alert("You haven't written anything!");
} else {
const newItem = document.createElement('li');
const newNode = document.createTextNode(input);
newItem.className = "closes";
newItem.appendChild(newNode);
document.getElementById("list").appendChild(newItem);
const img = document.createElement("img");
img.src = 'edit.png';
img.className = "edit";
const newSpan = document.createElement("span");
const xBtn = document.createTextNode("x");
newSpan.className = "close";
newSpan.appendChild(xBtn);
newItem.appendChild(img);
newItem.appendChild(newSpan);
document.getElementById("todotext").value = "";
}
}
body {
min-width: 850px;
font-family: sans-serif;
background-color: #ece0d9;
}
h1.title {
width: auto;
margin: auto;
padding: 25px;
text-align: center;
-webkit-text-stroke: 1px #460a1e; /* width and color */
font-family: sans-serif; color: white;
}
div.form {
display: flex;
padding: 10px;
width: 50%;
margin: auto;
}
input {
width: 75%;
padding: 10px 14px 11px 14px;
margin: 0;
border-radius: 0;
border-width: thin;
font-size: inherit;
}
input:focus {
border-radius: 0;
outline: none;
}
span.addTo {
width: 25%;
padding: 8px 14px 10px 14px;
margin: 0;
border-style: solid;
border-width: thin;
border-color: black;
border-left: none;
text-align: center;
background-color: rgb(236, 235, 235);
}
span.addTo:hover {
background-color: #e0e0e0;
cursor: pointer;
}
ul.list{
width: 50%;
display: table;
text-align: left;
padding: 0;
margin: auto;
}
ul.list li{
padding: 10px 10px;
background-color: snow;
clear: right;
margin: 0;
position: relative;
cursor: pointer;
}
ul.list li:nth-child(2n){
background-color: rgb(240, 239, 239);
}
ul.list li.checked:nth-child(2n){
text-decoration: line-through;
background-color: rgb(170, 168, 168);
}
ul li.checked {
text-decoration: line-through;
background-color: rgb(170, 168, 168);
}
img.edit {
position: absolute;
right: 40px;
top: 0;
padding: 1px;
width: 34px;
height: 36.4px;
cursor: pointer;
background-color: transparent;
color: rgb(75, 71, 71);
}
img.edit:hover {
padding: 0;
width: 34px;
height: 36.4px;
transition-property: background-color;
transition-duration: .3s;
border-style: ridge;
border-color: black;
border-width: 1px;
}
span.close {
position: absolute;
right: 0;
top: 0;
padding: 10px 14px 10px 14px;
cursor: pointer;
background-color: transparent;
color: rgb(75, 71, 71);
}
span.close:hover {
color: black;
padding: 9px 13px 9px 13px;
transition-property: background-color;
transition-duration: .3s;
border-style: ridge;
border-color: black;
border-width: 1px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<meta charset="en">
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1 class="title">To-Do List</h1>
<div class="form">
<input type="text" id="todotext">
<span onclick="printInput()" id="addTo" class="addTo">Add</span>
</div>
<ul style="list-style-type:none;" class="list" id="list">
<li hidden id="close">Clean room<img src="edit.png" class="edit"><span class="close">x</span></li>
</ul>
<script src="main.js">
</script>
</body>
</html>

How do I get my etch-a-sketch program to "listen" to this dropdown menu instead of the buttons?

I'm new to Stack Overflow. I hope that I'm doing this correctly. ❤
I'm working on an old Etch-a-Sketch JavaScript project from months ago and decided to rework the 'mobile' form of the project because I hadn't bothered to do so at the time. At first, I tried just moving the buttons to the top horizontally, but I didn't like any of the variations I tried. So I decided I'd be better off with a dropdown menu instead that would appear when the screen is 500px or smaller, replacing the buttons.
The dropdown menu is supposed to do exactly what the buttons do - when a certain mode is selected, that's the mode that the program is supposed to switch to. For example, when the "Party mode" button is clicked, the program switches to "party mode". I want the dropdown menu to behave similarly - when the "party mode" option is selected, the program should switch to "party mode".
My logic was that I needed a function that grabbed the value of the dropdown menu, and then an "if" condition would run that pretty much says "If the value is x, x mode should run; else if the value is y, y mode should run", and so on. I added the function to the existing window.onload function so it would run upon the window loading. This didn't work.
Note that the dropdown menu will, in the future, only appear when the screen size is 500px or less. In addition, I still have the buttons on the screen for all sizes, just for testing/debugging purposes. When I'm done and have this figured out, the buttons will have "display = 'none'" and be hidden for the "mobile size".
Anyway, so yeah, the program is still just listening to the buttons, and not the dropdown menu. That leads me to believe that I need to somehow turn "off" the button mode? If that's the case, how do I do that? If that's not the case, what am I supposed to do here? Any help or insight would be greatly appreciated. Thanks!
const defaultMode = 'default';
const defaultSize = 30;
const defaultColor = '#0b478b';
let currentMode = defaultMode;
let currentSize = defaultSize;
let currentColor = defaultColor;
// Sets the program's current mode
function setCurrentMode(newMode) {
activeButton(newMode);
currentMode = newMode;
}
// Sets the grid's size
function setCurrentSize(newSize) {
currentSize = newSize;
}
// Sets the color of the square (if in default mode)
function setCurrentColor(newColor) {
currentColor = newColor;
}
// Links the various HTML elements to this script
const sizeValue = document.querySelector('#sizevalue');
const sizeSlider = document.querySelector('#sizeslider');
const colorPicker = document.querySelector('#colorpicker');
const defaultBtn = document.querySelector('#default');
const partyBtn = document.querySelector('#party');
const grayBtn = document.querySelector('#grayscale');
const eraserBtn = document.querySelector('#eraser');
const clearBtn = document.querySelector('#clear');
const grid = document.querySelector('#maincontainer');
// DOM manipulations for buttons, color picker, and size slider
colorPicker.onchange = (e) => setCurrentColor(e.target.value);
defaultBtn.onclick = () => setCurrentMode('default');
partyBtn.onclick = () => setCurrentMode('party');
grayBtn.onclick = () => setCurrentMode('gray');
eraserBtn.onclick = () => setCurrentMode('eraser');
clearBtn.onclick = () => reloadGrid();
sizeSlider.onmousemove = (e) => updateSizeValue(e.target.value);
sizeSlider.onchange = (e) => changeSize(e.target.value);
// When the size is changed, we set the grid size, update the size value (text), and reload the grid.
function changeSize(num) {
setCurrentSize(num);
updateSizeValue(num);
reloadGrid();
}
// When we update the size value, the text changes to reflect the value. (It's a square, so the value is always the same for length and width).
function updateSizeValue(num) {
sizeValue.innerHTML = `${num} x ${num}`;
}
// When we reload the grid (which happens when "Clear grid" is pressed), we ensure that we clear the grid and that the size is still the current size.
function reloadGrid() {
clearGrid()
makeGrid(currentSize)
}
// When we clear the grid, it clears the grid.
function clearGrid() {
grid.innerHTML = ''
}
// Creates the base grid and includes the code that says "when the mouse goes over the squares, draw."
function makeGrid(size) {
grid.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${size}, 1fr)`;
for (i = 0; i < size * size; i++) {
let square = document.createElement('div');
square.addEventListener('mouseover', changeColor);
grid.appendChild(square);
}
}
// These are the conditions to set the color of the "pen" (squares)
function changeColor(e) {
if (currentMode === 'party') {
const randomR = Math.floor(Math.random() * 256);
const randomG = Math.floor(Math.random() * 256);
const randomB = Math.floor(Math.random() * 256);
e.target.style.backgroundColor = `rgb(${randomR}, ${randomG}, ${randomB})`;
} else if (currentMode === 'default') {
e.target.style.backgroundColor = currentColor;
} else if (currentMode === 'gray') {
e.target.style.backgroundColor = calculateGray(e);
} else if (currentMode === 'eraser') {
e.target.style.backgroundColor = 'white';
}
}
// Shading mode code
function calculateGray(e) {
let clr = returnRGB(e.target.style.backgroundColor);
if (!clr || clr[1] !== clr[2] || clr[1] !== clr[3]) {
return `rgb(255, 255, 255)`;
}
return clr[1] <= 0 ? `rgb(255, 255, 255)` : `rgb(${clr[1]-25}, ${clr[1]-25}, ${clr[1]-25})`;
}
function returnRGB(num) {
return num.match(/rgb\(([0-9]*), ([0-9]*), ([0-9]*)\)/);
}
// Changes the button styling to indicate which mode is the active mode
function activeButton(newMode) {
if (currentMode === 'party') {
partyBtn.classList.remove('active');
} else if (currentMode === 'default') {
defaultBtn.classList.remove('active');
} else if (currentMode === 'gray') {
grayBtn.classList.remove('active');
} else if (currentMode === 'eraser') {
eraserBtn.classList.remove('active');
}
if (newMode === 'party') {
partyBtn.classList.add('active');
} else if (newMode === 'default') {
defaultBtn.classList.add('active');
} else if (newMode === 'gray') {
grayBtn.classList.add('active');
} else if (newMode === 'eraser') {
eraserBtn.classList.add('active');
}
}
// Ensures that, when we load the page, we make the grid and activate the correct mode (default).
window.onload = () => {
makeGrid(defaultSize);
activeButton(defaultMode);
dropdownModeThing(document.getElementById('dropdown-mode').value);
}
// Code for the dropdown menu
function dropdownModeThing(val) {
if (val === 'default') {
setCurrentMode('default');
} else if (val === 'party') {
setCurrentMode('party');
} else if (val === 'shading') {
setCurrentMode('gray');
} else if (val === 'eraser') {
setCurrentMode('eraser');
} else if (val === 'clear') {
reloadGrid();
}
}
body,
html {
min-height: 100vh;
height: 100%;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 0;
padding: 0;
background-color: white;
overflow-x: hidden;
}
header {
text-align: center;
margin: 0;
border-bottom: 1px solid black;
background-color: #0b478b;
color: white;
padding: 10px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
p {
margin: 0;
}
h1 {
text-align: center;
margin: 0;
font-size: 2.5rem;
padding: 0;
}
#maincontainer {
background-color: white;
margin: 20px auto 10px auto;
display: grid;
border: 1px solid black;
width: 45vw;
height: 45vw;
min-height: 300px;
min-width: 300px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
.testing {
padding-top: 100%;
color: hsla(0, 0%, 68%, 0.596);
}
#btncontainer {
padding-top: 20px;
display: flex;
flex-direction: column;
justify-content: flex-start;
}
a {
color: #2aa5a1;
text-decoration: none;
}
a:hover {
color: white;
}
button {
background-color: #2aa5a1;
color: white;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: 1px solid black;
margin: 10px 15px;
padding: 8px 10px;
font-size: .9em;
transition: 0.3s;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
button:active {
background-color: #3F86D8;
color: white;
border: 1px solid black;
}
.active {
background-color: #3F86D8;
transition: 0.3s;
color: white;
border: 1px solid black;
}
button:hover {
background-color: #0b478b;
color: white;
border: 1px solid black;
opacity: 1;
}
#rightside {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
text-align: center;
min-height: 500px;
padding: 0;
margin: 0;
}
#sizevalue {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin-bottom: 0;
}
input[type=range] {
background-color: white;
height: 28px;
-webkit-appearance: none;
margin: 0;
margin-bottom: 35px;
width: 250px;
padding: 0;
}
input[type=range]:focus {}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000;
background: #3F86D8;
border-radius: 13px;
border: 0px solid #010101;
}
input[type=range]::-webkit-slider-thumb {
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #FFFFFF;
cursor: pointer;
-webkit-appearance: none;
margin-top: -5px;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #3F86D8;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000;
background: #3F86D8;
border-radius: 13px;
border: 0px solid #010101;
}
input[type=range]::-moz-range-thumb {
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #F3EEED;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #3F86D8;
border: 0px solid #010101;
border-radius: 26px;
box-shadow: 1px 1px 1px #000000;
}
input[type=range]::-ms-fill-upper {
background: #3F86D8;
border: 0px solid #010101;
border-radius: 26px;
box-shadow: 1px 1px 1px #000000;
}
input[type=range]::-ms-thumb {
margin-top: 1px;
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #F3EEED;
cursor: pointer;
}
input[type=range]:focus::-ms-fill-lower {
background: #3F86D8;
}
input[type=range]:focus::-ms-fill-upper {
background: #3F86D8;
}
main {
display: flex;
justify-content: center;
margin: 0;
margin-bottom: 20px;
padding: 0;
}
#colorpicker {
-webkit-appearance: none;
border-radius: 100vw;
width: 50px;
height: 50px;
padding: 0;
margin: 0 auto 10px auto;
overflow: hidden;
border: 1px solid black;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
input[type='color']:hover {
transform: scale(1.05);
}
input[type='color']::-webkit-color-swatch-wrapper {
padding: 0;
}
input[type='color']::-webkit-color-swatch {
border: none;
border-radius: 50px;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
/* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 50%;
right: 100%;
/* To the left of the tooltip */
margin-top: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent black transparent transparent;
}
footer {
color: white;
text-align: center;
background-color: #0b478b;
position: fixed;
bottom: 0;
width: 100%;
margin: 0;
padding-top: 10px;
padding-bottom: 15px;
}
#media (max-width: 500px) {
main {
flex-direction: column;
}
#btncontainer {
margin: 0 auto;
padding: 20px 10px 5px 10px;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
}
#btncontainer button {
margin: 0 3px;
height: 35px;
}
#colorpicker {
-webkit-appearance: none;
border-radius: 100px;
width: 35px;
height: 35px;
padding: 0;
margin: 0 auto 10px auto;
overflow: hidden;
border: 1px solid black;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CSS spreadsheet -->
<link href="styles.css" rel="stylesheet">
<title>Etch-a-Sketch</title>
</head>
<body>
<!-- Note that this is set up in various divs so
that we can use Flex to create our wanted layout. -->
<div id="entirepage">
<header>
<h1>Etch-a-Sketch</h1>
<p title="Testing">Select a color or a different mode, then select your size, and get drawing!</p>
</header>
<main>
<div id="btncontainer">
<select id="dropdown-mode">
<option value="default">Default mode</option>
<option value="party">Party mode</option>
<option value="shading">Shading</option>
<option value="eraser">Eraser mode</option>
<option value="clear">Clear grid</option>
</select>
<input type="color" id="colorpicker" value="#0b478b">
<button id="default">Default mode</button>
<button id="party">Party mode</button>
<button id="grayscale">Shading</button>
<button id="eraser">Eraser mode</button>
<button id="clear">Clear grid</button>
</div>
<div id="rightside">
<div id="maincontainer">
</div>
<label for="sizeslider" id="sizevalue">30 x 30</label>
<input type="range" min="1" max="100" value="30" id="sizeslider">
</div>
</main>
<footer>
<p>Created by Sara Dunlop (RiscloverYT)</p>
</footer>
</div>
<!-- JavaScript script -->
<script src="script.js"></script>
</body>
</html>
Luckily, there's an easy way to do that. Add this piece of code into your javascript file and see the magic.
const dropdown = document.getElementById('dropdown-mode');
dropdown.addEventListener('change', (e) => {
setCurrentMode(e.target.value);
});
Read more about change event here.

color changing button onclick

Okay so so far I have this page with a few buttons in it, whenever you click the button it turns red now i want to add that whenever you click it more times the color changes.
so for example: first the button is green, on the first click it turns red, on the third click it turns pink and so on.
I tried to do this with the set_onclick function I made and then multiple this code:
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
but i dont get it to work
page();
function onbuttonclicked(a) {
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);
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>
As you said the color of the button is dependent on how many times you clicked the button, and you will have to manage a local state for each button since there are many buttons
I think the the first thing you need is an object that will change the color like this, where the key is count and value is color
const obj = {
1 : "red",
2 : "blue"
3 : "pink"
4 : "skyblue"
...
...
...
}
and then change the color according to it
var colorMap = {
1 : "red",
2 : "blue",
3 : "pink",
4 : "hotpink",
5 : "brown",
6 : "yellow",
7 : "black"
}
page();
function page() {
document.body.style.backgroundColor = "grey";
createButtons(30);
}
document.body.addEventListener("click", (e)=>{
if(e.target.classList.contains("button")){
let currentbtnCount = parseInt(e.target.getAttribute("data-current-count")) + 1;
e.target.style.backgroundColor = colorMap[currentbtnCount] ? colorMap[currentbtnCount] : "black";
e.target.setAttribute("data-current-count", currentbtnCount);
}
})
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.setAttribute("data-current-count", "0")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>
And if you want complete random colors then here is another one
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
page();
function page() {
document.body.style.backgroundColor = "grey";
createButtons(30);
}
document.body.addEventListener("click", (e)=>{
if(e.target.classList.contains("button")){
e.target.style.backgroundColor = random_rgba();
}
})
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.setAttribute("data-current-count", "0")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>
Make a function that will count clicks and change the color of the button depending on the amount of the clicks.
You can just change a class like this:
document.querySelector(".MyElement").className = "MyClass";
hope You know that when searching for a class with querySelector You need to use '.' in front of the name of the class. If You try to find by ID either use querySelector with '#' in front of an ID or use getElementById:
document.getElementById("MyElement").className = "MyClass";
Example:
let counter = 0
document.getElemenetById('button').onclick = function(){
counter += 1
}
if (counter = 0) {
document.getElementById('button').className = 'red'
} else if (counter = 1) {
document.getElementById('button').className = 'blue'
}
or
let counter = 0
document.getElementById("button").addEventListener("click", counter += 1);
if (counter = 0) {
document.getElementById('button').className = 'red'
} else if (counter = 1) {
document.getElementById('button').className = 'blue'
}
or
let counter = 0
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
counter += 1
}
if (counter = 0) {
document.getElementById('button').className = 'red'
} else if (counter = 1) {
document.getElementById('button').className = 'blue'
}
</script>

CSS not working in firefox (or HTML displayed as simple text)

This is a simple webpage which compares two photographs and changes the one which is not clicked. The code is perfectly working in Chrome but in Firefox, HTML is being displayed as simple text and even links are not working.
CODE:-
* {
box-sizing: border-box;
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
}
header {
padding: 5px;
background-color: red;
color: white;
text-align: center;
font-family: Magneto;
-webkit-box-shadow: 4px 4px 7px grey;
-ms-box-shadow: 4px 4px 7px grey;
-moz-box-shadow: 4px 4px 7px grey;
-o-box-shadow: 4px 4px 7px grey;
box-shadow: 4px 4px 7px grey;
}
main {
margin: 10px;
}
#ques {
font-family: Cooper;
font-size: 125%;
font-weight: normal;
}
#imageContainer {
margin: auto;
text-align: center;
display: block;
}
.image {
width: 20%;
height: auto;
display: inline-block;
border: 2px solid black;
padding: 3px;
}
#or {
display: inline-block;
font-family: arial;
}
#leftImage {
margin-right: 10px;
}
#rightImage {
margin-left: 10px;
}
#media screen and (max-width: 600px) {
.image {
width: 30%;
}
}
aside {
font-size: 105%;
text-align: center;
margin: 20px 5px 5px 5px;
}
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
<link rel="stylesheet" type="text/css" href="D:/staticFbs.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var x = 1;
var y = 2;
$(document).ready(function() {
$("#leftImage").click(function() {
x = x + 2;
$("#rightImage").attr("src", "D:/staticFbp/boys/" + (x) + ".jpg");
if (x > y) {
var temp = y;
y = x;
x = temp;
};
});
$("#rightImage").click(function() {
y = y + 1;
$("#leftImage").attr("src", "D:/staticFbp/boys/" + (y) + ".jpg");
if (x > y) {
var temp = y;
y = x;
x = temp;
};
if (y > (x + 1)) {
x = x + 1;
};
});
});
</script>
</head>
<body>
<header>
<h1><abbr title="Ranking fun">SJSBook</abbr></h1>
</header>
<main>
<h3 id="ques">Q: Who is better?</h3>
<div id="imageContainer">
<img src="D:/staticFbp/boys/1.jpg" alt="Contestant 1" class="image" id="leftImage" />
<div id="or"><b>OR</b>
</div>
<img src="D:/staticFbp/boys/2.jpg" alt="Contestant 2" class="image" id="rightImage" />
</div>
<aside><em>Feel free as your votes will be confidential.</em>
</aside>
</main>
</body>
</html>
Preview of webpage in firefox
Use relative path not absolute Paths :
<link rel="stylesheet" type="text/css" href="staticFbs.css" />
You have to link that from your project. Put the CSS files to your project under root folder or whatever.
<link rel="stylesheet" type="text/css" href="../foldername/staticFbs.css" />
You are linking to your D-drive, in both your CSS-filepath and also in your jQuery.. This won't work when you put it online, so if you fix it on local, chances are it will also fix your Firefox-issue.

Categories