Sent information from backend (flask) to frontend without refreshing the page - javascript

I have an interface where I can draw a picture.
I have a machine learning model that can recognize this image.
What I want?
After clicking on the button "Recognize" I want to send the output from a machine learning model to an external interface i.e. a text field WITHOUT REFRESHING THE PAGE.
Before pressing the button "Recognize"
After pressing the button "Recognize"
With the code below I can print the output of the model to the terminal, but I need to send it to a text field.
paint.html
<html>
<head>
<meta charset="utf-8">
<title>Drawing App</title>
<link rel="stylesheet" href="static/style.css" type="text/css" media="screen" title="no title">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
</head>
<body>
<h2>Phone Number Recognition<img src="https://cdn1.iconfinder.com/data/icons/fatcow/32/painbrush.png" alt="" class="paint"></h2>
<canvas width="1024" height="256" id="mainCanvas"></canvas>
<div class="controls">
<button id="clear" onclick='clear_canvas()'>Clear</button>
<button id="recognize" onclick='recognize_number()'>Recognize</button>
<label id="label1"></label>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="static/main.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
style.css
* {
margin: 0;
padding: 0;
}
body {
background: #F5F5F5;
font-family: sans-serif;
height: 100%;
width: 100%;
}
h2 {
text-align: center;
margin: 20px;
font-family: 'Open Sans', sans-serif;
}
.paint {
padding-top: 2px;
}
/* CANVAS STYLING
===================*/
canvas {
display: block;
margin: 40px auto 10px;
border-radius: 5px;
border-left: 1px solid #E0E0E0;
border-right: 1px solid #E0E0E0;
border-top: 1px solid #E0E0E0;
box-shadow: 0 4px 0 0 #E0E0E0;
cursor: url(../img/cursor.png), crosshair;
}
.controls {
min-height: 60px;
margin: 0 auto;
width: 600px;
border-radius: 5px;
overflow: hidden;
}
ul {
list-style:none;
margin: 0;
float: left;
padding: 10px 0 20px;
width: 100%;
text-align: center;
}
/* BUTTON STYLES
==============*/
button {
background: #68B25B;
box-shadow: 0 3px 0 0 #6A845F;
color: #fff;
outline: none;
cursor: pointer;
text-shadow: 0 1px #6A845F;
display: block;
font-size: 16px;
line-height: 40px;
}
label {
background: #c7ebc1;
box-shadow: 0 3px 0 0 #6A845F;
color: rgb(0, 0, 0);
outline: none;
cursor: pointer;
text-shadow: 0 1px #6A845F;
display: block;
font-size: 16px;
line-height: 40px;
}
#clear {
border: none;
border-radius: 5px;
margin: 10px auto;
padding: 0 20px;
width: 160px;
height: 40px;
}
#recognize {
border: none;
border-radius: 5px;
margin: 10px auto;
padding: 0 20px;
width: 160px;
height: 40px;
}
#label1 {
border: none;
border-radius: 5px;
margin: 10px auto;
padding: 0 20px;
width: 260px;
height: 40px;
}
main.js
var colour = $(".selected").css("background-color");
var $canvas = $("canvas");
var context = $canvas[0].getContext("2d");
var lastEvent;
var mouseDown = false;
context.fillStyle = "white";
context.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
// On mouse events on the canvas
$canvas.mousedown(function (e) {
lastEvent = e;
mouseDown = true;
}).mousemove(function (e) {
// Draw lines
if (mouseDown) {
context.beginPath();
context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
context.lineTo(e.offsetX, e.offsetY);
context.strokeStyle = colour;
context.lineWidth = 10;
context.lineCap = 'round';
context.stroke();
lastEvent = e;
}
}).mouseup(function () {
mouseDown = false;
}).mouseleave(function () {
$canvas.mouseup();
});
// Clear the canvas when button is clicked
function clear_canvas() {
context.fillStyle = "white";
context.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
}
function recognize_number() {
var imgURL = $canvas[0].toDataURL('image/jpg');
$.ajax({
type: "POST",
url: "http://172.28.104.162:8080/hook",
data:{
imageBase64: imgURL
}
}).done(function() {
console.log('sent');
});
}
Flask
from flask import Flask, render_template, request
import os
import base64
import re
SAVE_PATH = '../data_from_flask'
app = Flask(__name__)
def some_model(img_path):
return 'some_output'
#app.route("/")
def home():
return render_template("paint.html")
#app.route('/hook', methods=['GET', 'POST'])
def recognize_image():
image_b64 = request.values['imageBase64']
image_data = re.sub('^data:image/.+;base64,', '', image_b64)
image_path = f"{SAVE_PATH}/flask_{len(os.listdir(SAVE_PATH))}.jpg"
with open(image_path, "wb") as fh:
fh.write(base64.decodebytes(bytes(image_data, encoding='UTF-8')))
recognized_number = some_model(img_path=image_path)
print(recognized_number)
return render_template('paint.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port='8080', debug=False)

You can get your element by its id and set the text to your computed output.
const labelElement = document.getElementById('label1');
function recognize_number() {
var imgURL = $canvas[0].toDataURL('image/jpg');
$.ajax({
type: "POST",
url: "http://172.28.104.162:8080/hook",
data:{
imageBase64: imgURL
}
}).done(function(output) {
labelElement.innerText = output;
});
}

Related

JavaScript chatbot - deleting the whole frame rather than just the message

I have the following webpage with chatbot inside. When you click a message it deletes it (pop up option) but this also happens (deletion option) when you try to click the outside of the frame and just inside the frame (not on a message) - which I want to prevent.
repl.it:
https://replit.com/#amalsheikh2309/WhisperedRelevantOutsourcing#index.html
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<style>
body {
background-color: #f2f2f2;
}
#chatroom {
width: 500px;
height: 400px;
border: 1px solid #ccc;
padding: 10px;
overflow: scroll;
font-family: Arial, sans-serif;
color: #333;
border: 1px solid #ccc;
box-shadow: 2px 2px 2px #ccc;
}
#messages {
height: 350px;
overflow: scroll;
background-color: #fff;
padding: 10px;
border-radius: 3px;
}
#messages div {
margin-bottom: 10px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 3px;
}
#message-input {
padding: 10px;
border-radius: 3px;
border: 1px solid #ccc;
box-sizing: border-box;
width: 100%;
margin-bottom: 10px;
}
#send-button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 3px;
cursor: pointer;
font-size: 16px;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="chatroom">
<div id="messages"></div>
<form>
<input type="text" id="message-input" placeholder="Type your message here...">
<button type="submit" id="send-button">Send</button>
</form>
</div>
<script>
const messageInput = document.getElementById('message-input');
const messagesContainer = document.getElementById('messages');
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
const message = messageInput.value;
messageInput.value = '';
const messageElement = document.createElement('div');
messageElement.innerText = message;
messagesContainer.appendChild(messageElement);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
});
document.getElementById("messages").addEventListener("click", function(e) {
if (e.target && e.target.nodeName == "DIV") {
var message = confirm("Are you sure you want to delete this message?");
if (message == true) {
e.target.remove();
}
}
});
</script>
</body>
</html>
I can see that the problem lies here
document.getElementById("messages").addEventListener("click", function(e) {
if (e.target && e.target.nodeName == "DIV") {
var message = confirm("Are you sure you want to delete this message?");
if (message == true) {
e.target.remove();
}
}
});
but I am not sure how to prevent it deleting the entire DIV and what to replace that part of the code with.
Thanks in advance.
ok so i figured it out
after you append messageElement text. add classlist of message
then in your if statement
if (e.target && e.target.classList.contains("message")) {
this should only activate click event when you click on a message
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<style>
body {
background-color: #f2f2f2;
}
#chatroom {
width: 500px;
height: 400px;
border: 1px solid #ccc;
padding: 10px;
overflow: scroll;
font-family: Arial, sans-serif;
color: #333;
border: 1px solid #ccc;
box-shadow: 2px 2px 2px #ccc;
}
#messages {
height: 350px;
overflow: scroll;
background-color: #fff;
padding: 10px;
border-radius: 3px;
}
#messages div {
margin-bottom: 10px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 3px;
}
#message-input {
padding: 10px;
border-radius: 3px;
border: 1px solid #ccc;
box-sizing: border-box;
width: 100%;
margin-bottom: 10px;
}
#send-button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 3px;
cursor: pointer;
font-size: 16px;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="chatroom">
<div id="messages"></div>
<form>
<input type="text" id="message-input" placeholder="Type your message here...">
<button type="submit" id="send-button">Send</button>
</form>
</div>
<script>
const messageInput = document.getElementById('message-input');
const messagesContainer = document.getElementById('messages');
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
const message = messageInput.value;
messageInput.value = '';
const messageElement = document.createElement('div');
messageElement.innerText = message;
messagesContainer.appendChild(messageElement);
messageElement.classList.add("message");
messagesContainer.scrollTop = messagesContainer.scrollHeight;
});
document.getElementById("messages").addEventListener("click", function(e) {
if (e.target && e.target.classList.contains("message")) {
var message = confirm("Are you sure you want to delete this message?");
if (message == true) {
e.target.remove();
}
}
});
</script>
</body>
</html>
You have added event listener to #messages div that's why it removes all children from the #messages div. Instead of #messages div you should add click event listener to single message.

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.

Button changing newest div item instead of the correct

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}')`

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.

Categories