Popular New Releases in Script Programming
rollup
v2.70.2
bash-it
v3.0.1
es5-shim
v4.5.15
wren
0.4.0
aviatorscript
AviatorScript 5.3.0
Popular Libraries in Script Programming
by rollup javascript
21476 NOASSERTION
Next-generation ES module bundler
by ruby ruby
19031 NOASSERTION
The Ruby Programming Language [mirror]
by you-dont-need javascript
13395 MIT
List of JavaScript methods which you can use natively + ESLint Plugin
by Bash-it shell
12822 MIT
A community Bash framework.
by alexanderepstein shell
8327 MIT
A collection of small bash scripts for heavy terminal users
by es-shims javascript
7083 MIT
ECMAScript 5 compatibility shims for legacy (and modern) JavaScript engines
by terser javascript
6919 NOASSERTION
🗜 JavaScript parser, mangler and compressor toolkit for ES6+
by magicmonty shell
6045 BSD-2-Clause
An informative and fancy bash prompt for Git users
by orangeduck c
5602 NOASSERTION
Higher level programming in C
Trending New libraries in Script Programming
by bobbyiliev html
1854 MIT
Free Introduction to Bash Scripting eBook
by juewuy shell
1811
One-click deployment and management of Clash services using Shell scripts in Linux environment
by rune-rs rust
855 NOASSERTION
An embeddable dynamic programming language for Rust.
by bigskysoftware javascript
707 BSD-2-Clause
a small scripting language for the web
by wangdoc shell
676
一本开源的 JavaScript 语言教程,全面介绍 ECMAScript 6 新引入的语法特性。
by fornwall rust
379 NOASSERTION
Run Rust files and expressions as scripts without any setup or compilation step.
by thevinter shell
288 MIT
A CLI tool for easy wallpaper management and image fetching
by adam-mcdaniel rust
238 Apache-2.0
Shell scripting that will knock your socks off
by theypsilon shell
219 GPL-3.0
All-in-one script for updating your MiSTer
Top Authors in Script Programming
1
36 Libraries
7387
2
12 Libraries
286
3
8 Libraries
396
4
8 Libraries
1052
5
7 Libraries
283
6
6 Libraries
57
7
5 Libraries
123
8
5 Libraries
11
9
5 Libraries
60
10
5 Libraries
59
1
36 Libraries
7387
2
12 Libraries
286
3
8 Libraries
396
4
8 Libraries
1052
5
7 Libraries
283
6
6 Libraries
57
7
5 Libraries
123
8
5 Libraries
11
9
5 Libraries
60
10
5 Libraries
59
Trending Kits in Script Programming
No Trending Kits are available at this moment for Script Programming
Trending Discussions on Script Programming
How to remove common words in a paragraph phrased using python
Whats up with eval()?
ReferenceError: document is not defined (JavaScript in VS Code)
What does "Convert overload list to single signature" mean?
How do I simplify this onclick function code?
Javascript delay not working. Tried too many things
npm is complaining about imports outside modules. What does that mean?
How to format the date with month/day/year from Sun May 04 1980 00:00:00 GMT+0500 (Pakistan Standard Time) in nodejs javascript mysql
Working with strings in C, strcat and the strange behavior of terminating null! (#beginner)
Strange "mouse:over" behavior after changing object attributes (left, top, radius etc.) via numeric input
QUESTION
How to remove common words in a paragraph phrased using python
Asked 2022-Mar-19 at 17:11I need a way to remove the common words within the above phrased content of a webpage. how to integrate such method.
third_headers = ' '.join([r.text for r in soup.find_all('h3')]) third_headers
I got an Output - 'HTML and CSS Data Analytics XML Tutorials JavaScript Programming Server Side Web Building Data Analytics XML Tutorials HTML CSS JavaScript Programming Server Side XML Character Sets Exercises Quizzes Courses Certificates Example Example Explained'
Need a new output without common words ( common words removed using from a common word corpus)
ANSWER
Answered 2022-Mar-19 at 17:11Assuming we have a corpus of common words in a list called CORPUS
:
1raw = 'HTML and CSS Data Analytics XML Tutorials JavaScript Programming Server Side Web Building Data Analytics XML Tutorials HTML CSS JavaScript Programming Server Side XML Character Sets Exercises Quizzes Courses Certificates Example Example Explained'
2
3
4CORPUS = ["And", "So", "If", "etc."] # assumed to have
5corpus = [w.lower() for w in CORPUS] # to lowercase
6
7words = raw.split()
8processed = [w for w in words if w.lower() not in corpus]
9
10print(processed)
11
QUESTION
Whats up with eval()?
Asked 2022-Mar-03 at 02:38I've seen a lot about how the eval()
function is evil; not a wise choice for HTML/JavaScript programming. I would like to use a function where I can pass in a string to have it read as a variable name, and eval()
seems to do just that, but I don't want to use a destructive function.
From what I understand, the issue with eval()
is that it can read third-party input as actual code, which opens a door for malicious activity. I have a map element that keeps track of location using strings for the location names. I also have large blocks of text assigned to variables so I can pull up a description of the current location easily. This seems like an acceptable time to use eval
, as the strings that I would be passing in would be provided by other parts of the code. Is this a fair judgement, or is there some other function that I should be using?
ANSWER
Answered 2022-Mar-03 at 02:27(Moving my comment as an answer)
An easy way to get around that is to save whatever variable you're interested in accessing in a javascript Object (i.e. key-value pairs), and access them via indexing. This simple use case doesn't need eval
.
QUESTION
ReferenceError: document is not defined (JavaScript in VS Code)
Asked 2022-Mar-02 at 10:36Im learning JS. Found a good video "JavaScript Programming - Full Course" and stucked at the 2nd part where I need to use DOM. I have the HTML document, in i refered to the JS file. Other stuff working well, but this:
let messageEL = document.getElementById("message-el")
Always get this error:
ReferenceError: document is not defined
I installed live server, and it works one time, than stops.
What can I do, to fix this? Do I need to download some extension? Please tell me the solution as simple as u can Im at the beginning of the learning path.
ANSWER
Answered 2022-Mar-02 at 10:36In your screenshot, you're attempting to run the script using Node.js (the server-side JavaScript executable).
Since you say you're running live-server, you should be looking at your browser instead, not trying to run your code via Node.
QUESTION
What does "Convert overload list to single signature" mean?
Asked 2022-Feb-25 at 22:49I am still learning some basics of javascript programming (and programming in general).
In my Angular Firebase project, I get the following typescript error (or rather proposed change in visual studio code, i.e. the lightbulb icon):
Convert overload list to single signature
It is referring to the following code:
1 updateUser(user: UserDocument): Observable<any> {
2 const ref = doc(this.firestore, 'users', user.uid);
3 return from(updateDoc(ref, { ...user }));
4 }
5
When I convert it, it appears like this:
1 updateUser(user: UserDocument): Observable<any> {
2 const ref = doc(this.firestore, 'users', user.uid);
3 return from(updateDoc(ref, { ...user }));
4 }
5 updateUser(...args: [user: UserDocument]): Observable<any> {
6 const ref = doc(this.firestore, 'users', user.uid);
7 return from(updateDoc(ref, { ...user }));
8 }
9
But now instead it is complaining Remove unused declaration of args
and also it complains about the last bid { ...user }
giving another lightbulb Import user from module "rxfire/auth"
I would appreciate it very much if someone gave a short explanation of what is going on?
Thank you!
EDIT: here are two screenshots just for extra clarity
ANSWER
Answered 2022-Feb-25 at 22:49In TypeScript, an overload refers to a function that can accept different types of parameters and return different types of values. For example, from the handbook, you could have
1 updateUser(user: UserDocument): Observable<any> {
2 const ref = doc(this.firestore, 'users', user.uid);
3 return from(updateDoc(ref, { ...user }));
4 }
5 updateUser(...args: [user: UserDocument]): Observable<any> {
6 const ref = doc(this.firestore, 'users', user.uid);
7 return from(updateDoc(ref, { ...user }));
8 }
9function makeDate(timestamp: number): Date;
10function makeDate(m: number, d: number, y: number): Date;
11
indicating that makeDate
either accepts one argument, a number, or three arguments, all numbers.
The
Convert overload list to single signature
warning appears to refer to a particular instance of this sort of thing. You can see the specifics here. It sounds like TypeScript determined that because multiple type declarations of the function use the same signature, there's no need for those multiple (overloaded) declarations, and to instead have only a single one.
The best approach would be to simply delete the other declaration, and use what you had originally.
If you wanted to use the rest parameters approach:
1 updateUser(user: UserDocument): Observable<any> {
2 const ref = doc(this.firestore, 'users', user.uid);
3 return from(updateDoc(ref, { ...user }));
4 }
5 updateUser(...args: [user: UserDocument]): Observable<any> {
6 const ref = doc(this.firestore, 'users', user.uid);
7 return from(updateDoc(ref, { ...user }));
8 }
9function makeDate(timestamp: number): Date;
10function makeDate(m: number, d: number, y: number): Date;
11updateUser(...args: [user: UserDocument]): Observable<any> {
12
then the single user would now be in args[0]
:
1 updateUser(user: UserDocument): Observable<any> {
2 const ref = doc(this.firestore, 'users', user.uid);
3 return from(updateDoc(ref, { ...user }));
4 }
5 updateUser(...args: [user: UserDocument]): Observable<any> {
6 const ref = doc(this.firestore, 'users', user.uid);
7 return from(updateDoc(ref, { ...user }));
8 }
9function makeDate(timestamp: number): Date;
10function makeDate(m: number, d: number, y: number): Date;
11updateUser(...args: [user: UserDocument]): Observable<any> {
12 updateUser(...args: [user: UserDocument]): Observable<any> {
13 const ref = doc(this.firestore, 'users', args[0].uid);
14 return from(updateDoc(ref, { ...args[0]}));
15 }
16
But updateUser(user: UserDocument)
is easier.
QUESTION
How do I simplify this onclick function code?
Asked 2022-Jan-13 at 16:03Just finished going through Head Start JavaScript Programming, figured I'd take a swing at building a "to-do" app from scratch. I've managed to get the following code to perform "correctly", but it is obviously super repetitive. My intention is to have text from an input field and dropdown to be logged together in a "to-do" list. Input field being the task and the dropdown providing a category/priority level. All suggestions/corrections would be deeply appreciated.
1function submitTo(){
2 var element = document.createElement("OL");
3 var input = document.getElementById("todotext").value;
4 var text = document.createTextNode(input);
5 element.appendChild(text);
6 document.getElementById("todo").appendChild(element);
7 createCategory();
8};
9
10
11function createCategory(){
12 var element = document.createElement("OL");
13 const selection = document.getElementById("catdropdown");
14 var option = selection.options[selection.selectedIndex].value;
15 var text = document.createTextNode(option);
16 element.appendChild(text);
17 document.getElementById("catdo").appendChild(element);
18};
1function submitTo(){
2 var element = document.createElement("OL");
3 var input = document.getElementById("todotext").value;
4 var text = document.createTextNode(input);
5 element.appendChild(text);
6 document.getElementById("todo").appendChild(element);
7 createCategory();
8};
9
10
11function createCategory(){
12 var element = document.createElement("OL");
13 const selection = document.getElementById("catdropdown");
14 var option = selection.options[selection.selectedIndex].value;
15 var text = document.createTextNode(option);
16 element.appendChild(text);
17 document.getElementById("catdo").appendChild(element);
18};body {
19 min-width: 650px;
20}
21
22div.form {
23 width: auto;
24 margin: auto;
25 padding: 10px;
26 text-align: center;
27}
28
29label {
30 margin: 10px;
31}
32
33h1.title {
34 color: saddlebrown;
35 width: auto;
36 margin: auto;
37 padding: 25px;
38 text-align: center;
39}
40
41div.list{
42 display: table;
43 width: auto;
44 margin: auto;
45 padding: 25px;
46}
47
48div.column{
49 display: table-cell;
50 text-align: center;
51 width: 200px;
52 padding: 10x;
53 margin: 0px 10px 10px 0px;
54}
55
56div.column ul {
57 text-align: left;
58 padding: 0px;
59}
1function submitTo(){
2 var element = document.createElement("OL");
3 var input = document.getElementById("todotext").value;
4 var text = document.createTextNode(input);
5 element.appendChild(text);
6 document.getElementById("todo").appendChild(element);
7 createCategory();
8};
9
10
11function createCategory(){
12 var element = document.createElement("OL");
13 const selection = document.getElementById("catdropdown");
14 var option = selection.options[selection.selectedIndex].value;
15 var text = document.createTextNode(option);
16 element.appendChild(text);
17 document.getElementById("catdo").appendChild(element);
18};body {
19 min-width: 650px;
20}
21
22div.form {
23 width: auto;
24 margin: auto;
25 padding: 10px;
26 text-align: center;
27}
28
29label {
30 margin: 10px;
31}
32
33h1.title {
34 color: saddlebrown;
35 width: auto;
36 margin: auto;
37 padding: 25px;
38 text-align: center;
39}
40
41div.list{
42 display: table;
43 width: auto;
44 margin: auto;
45 padding: 25px;
46}
47
48div.column{
49 display: table-cell;
50 text-align: center;
51 width: 200px;
52 padding: 10x;
53 margin: 0px 10px 10px 0px;
54}
55
56div.column ul {
57 text-align: left;
58 padding: 0px;
59}<!DOCTYPE html>
60<html>
61 <head>
62 <title>To-Do List</title>
63 <meta charset="en">
64 <link rel="stylesheet" href="main.css">
65 <script src="main.js"></script>
66 </head>
67 <body>
68 <h1 class="title">To-do List</h1>
69 <div class="form">
70 <label>
71 <input type="text" id="todotext">
72 </label>
73 <label>
74 <select name="dropdown" id="catdropdown">
75 <option value="" selected>Choose a category</option>
76 <option value="Work">Work</option>
77 <option value="House">House</option>
78 <option value="Honey-Do">Honey-Do</option>
79 </select>
80 </label>
81 <label>
82 <button type="submit" onclick="submitTo()">Submit</button>
83 </label>
84 </div>
85
86 <div class="list">
87 <div class="column">
88 <h2>To-Do:</h2>
89 <ul id="todo">
90
91 </ul>
92
93 </div>
94
95 <div class="column">
96 <h2>Category:</h2>
97 <ul id="catdo">
98
99 </ul>
100
101 </div>
102 </div>
103 <div class="list">
104 <div class="column">
105 <h2>Completed</h2>
106 <ul align="center">Checkbox and Log</p>
107
108 </div>
109
110
111 </body>
112</html>
ANSWER
Answered 2022-Jan-13 at 16:03You could try something like this:
Replace your lists with a table, this allows you to utilize the table structure in two ways. 1. easy alignment ability and 2. access to a heading and a body .
Next create an onclick function that that first captures the values just like you have before then creates a newItem that is a just a template literal with the proper table structure and uses the values you just saved.
Finally you just append the new item before the end of the table body.
1function submitTo(){
2 var element = document.createElement("OL");
3 var input = document.getElementById("todotext").value;
4 var text = document.createTextNode(input);
5 element.appendChild(text);
6 document.getElementById("todo").appendChild(element);
7 createCategory();
8};
9
10
11function createCategory(){
12 var element = document.createElement("OL");
13 const selection = document.getElementById("catdropdown");
14 var option = selection.options[selection.selectedIndex].value;
15 var text = document.createTextNode(option);
16 element.appendChild(text);
17 document.getElementById("catdo").appendChild(element);
18};body {
19 min-width: 650px;
20}
21
22div.form {
23 width: auto;
24 margin: auto;
25 padding: 10px;
26 text-align: center;
27}
28
29label {
30 margin: 10px;
31}
32
33h1.title {
34 color: saddlebrown;
35 width: auto;
36 margin: auto;
37 padding: 25px;
38 text-align: center;
39}
40
41div.list{
42 display: table;
43 width: auto;
44 margin: auto;
45 padding: 25px;
46}
47
48div.column{
49 display: table-cell;
50 text-align: center;
51 width: 200px;
52 padding: 10x;
53 margin: 0px 10px 10px 0px;
54}
55
56div.column ul {
57 text-align: left;
58 padding: 0px;
59}<!DOCTYPE html>
60<html>
61 <head>
62 <title>To-Do List</title>
63 <meta charset="en">
64 <link rel="stylesheet" href="main.css">
65 <script src="main.js"></script>
66 </head>
67 <body>
68 <h1 class="title">To-do List</h1>
69 <div class="form">
70 <label>
71 <input type="text" id="todotext">
72 </label>
73 <label>
74 <select name="dropdown" id="catdropdown">
75 <option value="" selected>Choose a category</option>
76 <option value="Work">Work</option>
77 <option value="House">House</option>
78 <option value="Honey-Do">Honey-Do</option>
79 </select>
80 </label>
81 <label>
82 <button type="submit" onclick="submitTo()">Submit</button>
83 </label>
84 </div>
85
86 <div class="list">
87 <div class="column">
88 <h2>To-Do:</h2>
89 <ul id="todo">
90
91 </ul>
92
93 </div>
94
95 <div class="column">
96 <h2>Category:</h2>
97 <ul id="catdo">
98
99 </ul>
100
101 </div>
102 </div>
103 <div class="list">
104 <div class="column">
105 <h2>Completed</h2>
106 <ul align="center">Checkbox and Log</p>
107
108 </div>
109
110
111 </body>
112</html>const submitBtn = document.getElementById("submit-btn");
113submitBtn.addEventListener("click", function() {
114 let input = document.getElementById("todotext").value,
115 selection = document.getElementById("catdropdown"),
116 option = selection.options[selection.selectedIndex].value,
117 newItem = `
118 <tr>
119 <td>${input}</td>
120 <td>${option}</td>
121 </tr>
122 `;
123 document.querySelector(".main-body").insertAdjacentHTML("beforeend", newItem);
124});
1function submitTo(){
2 var element = document.createElement("OL");
3 var input = document.getElementById("todotext").value;
4 var text = document.createTextNode(input);
5 element.appendChild(text);
6 document.getElementById("todo").appendChild(element);
7 createCategory();
8};
9
10
11function createCategory(){
12 var element = document.createElement("OL");
13 const selection = document.getElementById("catdropdown");
14 var option = selection.options[selection.selectedIndex].value;
15 var text = document.createTextNode(option);
16 element.appendChild(text);
17 document.getElementById("catdo").appendChild(element);
18};body {
19 min-width: 650px;
20}
21
22div.form {
23 width: auto;
24 margin: auto;
25 padding: 10px;
26 text-align: center;
27}
28
29label {
30 margin: 10px;
31}
32
33h1.title {
34 color: saddlebrown;
35 width: auto;
36 margin: auto;
37 padding: 25px;
38 text-align: center;
39}
40
41div.list{
42 display: table;
43 width: auto;
44 margin: auto;
45 padding: 25px;
46}
47
48div.column{
49 display: table-cell;
50 text-align: center;
51 width: 200px;
52 padding: 10x;
53 margin: 0px 10px 10px 0px;
54}
55
56div.column ul {
57 text-align: left;
58 padding: 0px;
59}<!DOCTYPE html>
60<html>
61 <head>
62 <title>To-Do List</title>
63 <meta charset="en">
64 <link rel="stylesheet" href="main.css">
65 <script src="main.js"></script>
66 </head>
67 <body>
68 <h1 class="title">To-do List</h1>
69 <div class="form">
70 <label>
71 <input type="text" id="todotext">
72 </label>
73 <label>
74 <select name="dropdown" id="catdropdown">
75 <option value="" selected>Choose a category</option>
76 <option value="Work">Work</option>
77 <option value="House">House</option>
78 <option value="Honey-Do">Honey-Do</option>
79 </select>
80 </label>
81 <label>
82 <button type="submit" onclick="submitTo()">Submit</button>
83 </label>
84 </div>
85
86 <div class="list">
87 <div class="column">
88 <h2>To-Do:</h2>
89 <ul id="todo">
90
91 </ul>
92
93 </div>
94
95 <div class="column">
96 <h2>Category:</h2>
97 <ul id="catdo">
98
99 </ul>
100
101 </div>
102 </div>
103 <div class="list">
104 <div class="column">
105 <h2>Completed</h2>
106 <ul align="center">Checkbox and Log</p>
107
108 </div>
109
110
111 </body>
112</html>const submitBtn = document.getElementById("submit-btn");
113submitBtn.addEventListener("click", function() {
114 let input = document.getElementById("todotext").value,
115 selection = document.getElementById("catdropdown"),
116 option = selection.options[selection.selectedIndex].value,
117 newItem = `
118 <tr>
119 <td>${input}</td>
120 <td>${option}</td>
121 </tr>
122 `;
123 document.querySelector(".main-body").insertAdjacentHTML("beforeend", newItem);
124});body {
125 min-width: 650px;
126}
127
128div.form {
129 width: auto;
130 margin: auto;
131 padding: 10px;
132 text-align: center;
133}
134
135label {
136 margin: 10px;
137}
138
139h1.title {
140 color: saddlebrown;
141 width: auto;
142 margin: auto;
143 padding: 25px;
144 text-align: center;
145}
146
147div.list{
148 display: table;
149 width: auto;
150 margin: auto;
151 padding: 25px;
152}
153
154div.column{
155 display: table-cell;
156 text-align: center;
157 width: 200px;
158 padding: 10x;
159 margin: 0px 10px 10px 0px;
160}
161
162div.column ul {
163 text-align: left;
164 padding: 0px;
165}
166
167.main-table {
168 width: 50%;
169 margin: 0 auto;
170}
171
172.main-table thead, .main-table tbody {
173 text-align: center;
174}
1function submitTo(){
2 var element = document.createElement("OL");
3 var input = document.getElementById("todotext").value;
4 var text = document.createTextNode(input);
5 element.appendChild(text);
6 document.getElementById("todo").appendChild(element);
7 createCategory();
8};
9
10
11function createCategory(){
12 var element = document.createElement("OL");
13 const selection = document.getElementById("catdropdown");
14 var option = selection.options[selection.selectedIndex].value;
15 var text = document.createTextNode(option);
16 element.appendChild(text);
17 document.getElementById("catdo").appendChild(element);
18};body {
19 min-width: 650px;
20}
21
22div.form {
23 width: auto;
24 margin: auto;
25 padding: 10px;
26 text-align: center;
27}
28
29label {
30 margin: 10px;
31}
32
33h1.title {
34 color: saddlebrown;
35 width: auto;
36 margin: auto;
37 padding: 25px;
38 text-align: center;
39}
40
41div.list{
42 display: table;
43 width: auto;
44 margin: auto;
45 padding: 25px;
46}
47
48div.column{
49 display: table-cell;
50 text-align: center;
51 width: 200px;
52 padding: 10x;
53 margin: 0px 10px 10px 0px;
54}
55
56div.column ul {
57 text-align: left;
58 padding: 0px;
59}<!DOCTYPE html>
60<html>
61 <head>
62 <title>To-Do List</title>
63 <meta charset="en">
64 <link rel="stylesheet" href="main.css">
65 <script src="main.js"></script>
66 </head>
67 <body>
68 <h1 class="title">To-do List</h1>
69 <div class="form">
70 <label>
71 <input type="text" id="todotext">
72 </label>
73 <label>
74 <select name="dropdown" id="catdropdown">
75 <option value="" selected>Choose a category</option>
76 <option value="Work">Work</option>
77 <option value="House">House</option>
78 <option value="Honey-Do">Honey-Do</option>
79 </select>
80 </label>
81 <label>
82 <button type="submit" onclick="submitTo()">Submit</button>
83 </label>
84 </div>
85
86 <div class="list">
87 <div class="column">
88 <h2>To-Do:</h2>
89 <ul id="todo">
90
91 </ul>
92
93 </div>
94
95 <div class="column">
96 <h2>Category:</h2>
97 <ul id="catdo">
98
99 </ul>
100
101 </div>
102 </div>
103 <div class="list">
104 <div class="column">
105 <h2>Completed</h2>
106 <ul align="center">Checkbox and Log</p>
107
108 </div>
109
110
111 </body>
112</html>const submitBtn = document.getElementById("submit-btn");
113submitBtn.addEventListener("click", function() {
114 let input = document.getElementById("todotext").value,
115 selection = document.getElementById("catdropdown"),
116 option = selection.options[selection.selectedIndex].value,
117 newItem = `
118 <tr>
119 <td>${input}</td>
120 <td>${option}</td>
121 </tr>
122 `;
123 document.querySelector(".main-body").insertAdjacentHTML("beforeend", newItem);
124});body {
125 min-width: 650px;
126}
127
128div.form {
129 width: auto;
130 margin: auto;
131 padding: 10px;
132 text-align: center;
133}
134
135label {
136 margin: 10px;
137}
138
139h1.title {
140 color: saddlebrown;
141 width: auto;
142 margin: auto;
143 padding: 25px;
144 text-align: center;
145}
146
147div.list{
148 display: table;
149 width: auto;
150 margin: auto;
151 padding: 25px;
152}
153
154div.column{
155 display: table-cell;
156 text-align: center;
157 width: 200px;
158 padding: 10x;
159 margin: 0px 10px 10px 0px;
160}
161
162div.column ul {
163 text-align: left;
164 padding: 0px;
165}
166
167.main-table {
168 width: 50%;
169 margin: 0 auto;
170}
171
172.main-table thead, .main-table tbody {
173 text-align: center;
174}<!DOCTYPE html>
175<html>
176 <head>
177 <title>To-Do List</title>
178 <meta charset="en">
179 <link rel="stylesheet" href="main.css">
180 <script src="main.js"></script>
181 </head>
182 <body>
183 <h1 class="title">To-do List</h1>
184 <div class="form">
185 <label>
186 <input type="text" id="todotext">
187 </label>
188 <label>
189 <select name="dropdown" id="catdropdown">
190 <option value="" selected>Choose a category</option>
191 <option value="Work">Work</option>
192 <option value="House">House</option>
193 <option value="Honey-Do">Honey-Do</option>
194 </select>
195 </label>
196 <label>
197 <button id="submit-btn" type="submit">Submit</button>
198 </label>
199 </div>
200
201 <table class="main-table">
202 <thead>
203 <tr>
204 <td>To Do:</td>
205 <td>Category</td>
206 </tr>
207 </thead>
208 <tbody class="main-body">
209
210 </tbody>
211 </table>
212
213 <div class="list">
214 <div class="column">
215 <h2>Completed</h2>
216 <ul align="center">Checkbox and Log</p>
217
218 </div>
219
220
221 </body>
222</html>
QUESTION
Javascript delay not working. Tried too many things
Asked 2021-Nov-21 at 07:55I am new with JavaScript programming. I am making a program for deaf and blind children community. It is text to display Letters program. It split text and show image on screen.
How it works:HTML and JavaScript base program. Input sentence taken from user. JavaScript split it and send relevant image name to HTML for display.
Problem:It shows all images at once without delay. When I use alert() it shows all images are being displayed. 3rd day going on I tried to implement delay timebase substraction or settimeout but not working. Perhaps I am doing something wrong. I need community help to fix this.
Code:1<html lang="en">
2 <head>
3 <!-- Bootstrap CSS -->
4 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
5 <link rel="stylesheet" href="index.css" />
6 <!-- Optional JavaScript -->
7 <!-- jQuery first, then Popper.js, then Bootstrap JS -->
8 <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
9
10 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
11
12 <title>Image Changer</title>
13 </head>
14// How to change image SCR through javascript.
15
16<body>
17
18<input id="txt" name="txt" type="textbox" />
19
20<img id="image1" src="./multimedia/alphabets/0.jpg" style="width:100px">
21
22<button onclick="imagechange((document.getElementById('txt').value) , document.getElementById('image1.scr'))">Button</button>
23
24
25<script type="text/javascript">
26 function imagechange(txt,image1){
27
28 var txt1 = "";
29 var txt2 = "";
30 var imagefolderlocation = "./multimedia/alphabets/";
31 for (var i = 0; i < txt.length;i++) {
32 txt1 = txt.charAt(i).toUpperCase();
33
34 alert(txt1);
35 document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
36 if(txt1 == " " )
37 document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
38
39 }
40 }
41
42
43</script>
44
45</body>
46</html>
47
ANSWER
Answered 2021-Nov-21 at 07:33setTimeout
is async so that's probably the reason it did not work. To make it work, you can do something like this
1<html lang="en">
2 <head>
3 <!-- Bootstrap CSS -->
4 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
5 <link rel="stylesheet" href="index.css" />
6 <!-- Optional JavaScript -->
7 <!-- jQuery first, then Popper.js, then Bootstrap JS -->
8 <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
9
10 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
11
12 <title>Image Changer</title>
13 </head>
14// How to change image SCR through javascript.
15
16<body>
17
18<input id="txt" name="txt" type="textbox" />
19
20<img id="image1" src="./multimedia/alphabets/0.jpg" style="width:100px">
21
22<button onclick="imagechange((document.getElementById('txt').value) , document.getElementById('image1.scr'))">Button</button>
23
24
25<script type="text/javascript">
26 function imagechange(txt,image1){
27
28 var txt1 = "";
29 var txt2 = "";
30 var imagefolderlocation = "./multimedia/alphabets/";
31 for (var i = 0; i < txt.length;i++) {
32 txt1 = txt.charAt(i).toUpperCase();
33
34 alert(txt1);
35 document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
36 if(txt1 == " " )
37 document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
38
39 }
40 }
41
42
43</script>
44
45</body>
46</html>
47<script type="text/javascript">
48 function delay(time) {
49 return new Promise(function(resolve) {
50 setTimeout(resolve, time);
51 });
52 }
53
54 async function imagechange(txt,image1){
55 var txt1 = "";
56 var txt2 = "";
57 var imagefolderlocation = "./multimedia/alphabets/";
58 for (var i = 0; i < txt.length;i++) {
59 txt1 = txt.charAt(i).toUpperCase();
60 await delay(1000);
61 document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
62 if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
63 }
64 }
65</script>
66
I made a delay promise from the setTimeout
and made your imageChange
function async so I can await the delay promise during each loop.
QUESTION
npm is complaining about imports outside modules. What does that mean?
Asked 2021-Jul-07 at 20:22As a personal project, I am trying to learn some basic javascript programming by implementing an online version of the card game "Great Dalmuti".
Right now, I'm trying to implement some basic elements from the game using TDD. You can see the current state of my code at: https://github.com/spierepf/great-dalmuti
The issue that I am having is with the statement:
1import { INVALID_MOVE } from 'boardgame.io/core';
2
which I copy-pasted from the boardgame.io tutorial at: https://boardgame.io/documentation/#/tutorial?id=validating-moves
The error I am getting is:
1import { INVALID_MOVE } from 'boardgame.io/core';
2$ npm test
3
4> great-dalmuti@1.0.0 test
5> mocha
6
7(node:21353) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
8(Use `node --trace-warnings ...` to show where the warning was created)
9
10/home/peter/Nextcloud/boardgame.io/great-dalmuti/test/Game.test.js:3
11import { INVALID_MOVE } from 'boardgame.io/core';
12^^^^^^
13
14SyntaxError: Cannot use import statement outside a module
15 at wrapSafe (internal/modules/cjs/loader.js:979:16)
16 at Module._compile (internal/modules/cjs/loader.js:1027:27)
17 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
18 at Module.load (internal/modules/cjs/loader.js:928:32)
19 at Function.Module._load (internal/modules/cjs/loader.js:769:14)
20 at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
21 at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
22 at async Loader.import (internal/modules/esm/loader.js:166:24)
23 at async formattedImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:7:14)
24 at async Object.exports.requireOrImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:48:32)
25 at async Object.exports.loadFilesAsync (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:74:20)
26 at async singleRun (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run-helpers.js:125:3)
27 at async Object.exports.handler (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run.js:366:5)
28
What I find online involves renaming files with different extensions (mostly .cjs
and .mjs
) or adding <script/>
tags, or making the whole project into a module by editing package.json
. None of these options have worked so far.
I've followed the complete boardgame.io tutorial for tic-tac-toe and have gotten it working successfully. It doesn't appear to involve modules, exotic extensions, or special tags. What the tutorial doesn't involve is TDD or automated tests.
ANSWER
Answered 2021-Jul-07 at 20:22Node cannot execute import
and export
statements natively. There are 2-3 ways to do it as you said in the post itself, like 1) change extension to mjs, 2) change package.json to make project a module. I think you are not able to use that properly because you are running test cases.
So, the best thing for you would be to add babel support to your repository.
1import { INVALID_MOVE } from 'boardgame.io/core';
2$ npm test
3
4> great-dalmuti@1.0.0 test
5> mocha
6
7(node:21353) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
8(Use `node --trace-warnings ...` to show where the warning was created)
9
10/home/peter/Nextcloud/boardgame.io/great-dalmuti/test/Game.test.js:3
11import { INVALID_MOVE } from 'boardgame.io/core';
12^^^^^^
13
14SyntaxError: Cannot use import statement outside a module
15 at wrapSafe (internal/modules/cjs/loader.js:979:16)
16 at Module._compile (internal/modules/cjs/loader.js:1027:27)
17 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
18 at Module.load (internal/modules/cjs/loader.js:928:32)
19 at Function.Module._load (internal/modules/cjs/loader.js:769:14)
20 at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
21 at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
22 at async Loader.import (internal/modules/esm/loader.js:166:24)
23 at async formattedImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:7:14)
24 at async Object.exports.requireOrImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:48:32)
25 at async Object.exports.loadFilesAsync (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:74:20)
26 at async singleRun (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run-helpers.js:125:3)
27 at async Object.exports.handler (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run.js:366:5)
28npm install --save-dev @babel/cli @babel/core @babel/node @babel/register @babel/preset-env
29
Make a file called .babelrc
:
1import { INVALID_MOVE } from 'boardgame.io/core';
2$ npm test
3
4> great-dalmuti@1.0.0 test
5> mocha
6
7(node:21353) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
8(Use `node --trace-warnings ...` to show where the warning was created)
9
10/home/peter/Nextcloud/boardgame.io/great-dalmuti/test/Game.test.js:3
11import { INVALID_MOVE } from 'boardgame.io/core';
12^^^^^^
13
14SyntaxError: Cannot use import statement outside a module
15 at wrapSafe (internal/modules/cjs/loader.js:979:16)
16 at Module._compile (internal/modules/cjs/loader.js:1027:27)
17 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
18 at Module.load (internal/modules/cjs/loader.js:928:32)
19 at Function.Module._load (internal/modules/cjs/loader.js:769:14)
20 at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
21 at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
22 at async Loader.import (internal/modules/esm/loader.js:166:24)
23 at async formattedImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:7:14)
24 at async Object.exports.requireOrImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:48:32)
25 at async Object.exports.loadFilesAsync (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:74:20)
26 at async singleRun (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run-helpers.js:125:3)
27 at async Object.exports.handler (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run.js:366:5)
28npm install --save-dev @babel/cli @babel/core @babel/node @babel/register @babel/preset-env
29{
30 "presets": ["@babel/preset-env"]
31}
32
Run with:
1import { INVALID_MOVE } from 'boardgame.io/core';
2$ npm test
3
4> great-dalmuti@1.0.0 test
5> mocha
6
7(node:21353) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
8(Use `node --trace-warnings ...` to show where the warning was created)
9
10/home/peter/Nextcloud/boardgame.io/great-dalmuti/test/Game.test.js:3
11import { INVALID_MOVE } from 'boardgame.io/core';
12^^^^^^
13
14SyntaxError: Cannot use import statement outside a module
15 at wrapSafe (internal/modules/cjs/loader.js:979:16)
16 at Module._compile (internal/modules/cjs/loader.js:1027:27)
17 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
18 at Module.load (internal/modules/cjs/loader.js:928:32)
19 at Function.Module._load (internal/modules/cjs/loader.js:769:14)
20 at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
21 at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
22 at async Loader.import (internal/modules/esm/loader.js:166:24)
23 at async formattedImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:7:14)
24 at async Object.exports.requireOrImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:48:32)
25 at async Object.exports.loadFilesAsync (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:74:20)
26 at async singleRun (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run-helpers.js:125:3)
27 at async Object.exports.handler (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run.js:366:5)
28npm install --save-dev @babel/cli @babel/core @babel/node @babel/register @babel/preset-env
29{
30 "presets": ["@babel/preset-env"]
31}
32mocha --compilers js:@babel/register
33
you can change the test
script to this as well.
You can follow a more detailed blog, for example this
QUESTION
How to format the date with month/day/year from Sun May 04 1980 00:00:00 GMT+0500 (Pakistan Standard Time) in nodejs javascript mysql
Asked 2021-Jun-07 at 12:10This is the code of the main page like in the screenshot. Using mysql to get that data, it is a CRUD application with nodejs, express, mysql and bootstrap. Don't know how to format the date to (month/day/year) instead of (Sun May 04 1980 00:00:00 GMT+0500 (Pakistan Standard Time)). Please help. New to javascript programming, so i am struggling :(
1<div class="row">
2 <div class="col-6"><h1>Users</h1></div>
3 <div class="col-6 d-flex justify-content-end">
4 <a href="/adduser" type="button" class="btn btn-primary align-self-center">+ add new user</a>
5 </div>
6</div>
7<table class="table table-bordered">
8 <thead class="thead-dark">
9 <tr>
10 <th scope="col">#</th>
11 <th scope="col">First Name</th>
12 <th scope="col">Last Name</th>
13 <th scope="col">DoB</th>
14 <th scope="col">Phone</th>
15 <th scope="col" class="text-end">Action</th>
16 </tr>
17 </thead>
18 <tbody>
19
20 {{#each rows}}
21 <tr>
22 <th scope="row">{{this.id}}</th>
23 <td>{{this.first_name}}</td>
24 <td>{{this.last_name}}</td>
25 <td>{{this.dob}}</td>
26 <td>{{this.phone}}</td>
27 <td class="text-end">
28 <a href="/viewuser/{{this.id}}" type="button" class="btn btn-light btn-small"><i class="bi bi-eye"></i> View</a>
29 <a href="/edituser/{{this.id}}" type="button" class="btn btn-light btn-small"><i class="bi bi-pencil-square"></i> Edit</a>
30 <a href="/{{this.id}}" type="button" class="btn btn-light btn-small"><i class="bi bi-person-x"></i> Delete</a>
31 </td>
32 </tr>
33 {{/each}}
34
35 </tbody>
36</table>
37
38// View users
39exports.view = (req, res) => {
40 pool.getConnection((err, connection) =>{
41 if(err) throw err; // not connected
42 console.log('DB connected as ID' + connection.threadId);
43 // User the connection
44 connection.query('SELECT * FROM users ', (err, rows)=> {
45 // When done with the connection, release it
46 connection.release();
47 if(!err){
48 let removedUser = req.query.removed;
49 res.render('home', { rows, removedUser });
50 }
51 else {
52 console.log(err);
53 }
54 console.log('The data from user table: \n', rows);
55 });
56});
57}
58
ANSWER
Answered 2021-Jun-07 at 12:10You can update the Date format in your SQL query while fetching values. Simply mention the required date format and pass the value to your view engine.
1<div class="row">
2 <div class="col-6"><h1>Users</h1></div>
3 <div class="col-6 d-flex justify-content-end">
4 <a href="/adduser" type="button" class="btn btn-primary align-self-center">+ add new user</a>
5 </div>
6</div>
7<table class="table table-bordered">
8 <thead class="thead-dark">
9 <tr>
10 <th scope="col">#</th>
11 <th scope="col">First Name</th>
12 <th scope="col">Last Name</th>
13 <th scope="col">DoB</th>
14 <th scope="col">Phone</th>
15 <th scope="col" class="text-end">Action</th>
16 </tr>
17 </thead>
18 <tbody>
19
20 {{#each rows}}
21 <tr>
22 <th scope="row">{{this.id}}</th>
23 <td>{{this.first_name}}</td>
24 <td>{{this.last_name}}</td>
25 <td>{{this.dob}}</td>
26 <td>{{this.phone}}</td>
27 <td class="text-end">
28 <a href="/viewuser/{{this.id}}" type="button" class="btn btn-light btn-small"><i class="bi bi-eye"></i> View</a>
29 <a href="/edituser/{{this.id}}" type="button" class="btn btn-light btn-small"><i class="bi bi-pencil-square"></i> Edit</a>
30 <a href="/{{this.id}}" type="button" class="btn btn-light btn-small"><i class="bi bi-person-x"></i> Delete</a>
31 </td>
32 </tr>
33 {{/each}}
34
35 </tbody>
36</table>
37
38// View users
39exports.view = (req, res) => {
40 pool.getConnection((err, connection) =>{
41 if(err) throw err; // not connected
42 console.log('DB connected as ID' + connection.threadId);
43 // User the connection
44 connection.query('SELECT * FROM users ', (err, rows)=> {
45 // When done with the connection, release it
46 connection.release();
47 if(!err){
48 let removedUser = req.query.removed;
49 res.render('home', { rows, removedUser });
50 }
51 else {
52 console.log(err);
53 }
54 console.log('The data from user table: \n', rows);
55 });
56});
57}
58connection.query('SELECT all_required_columns, DATE_FORMAT(dob, "%m/%d/%y") as dob FROM users ', (err, rows)=> {
59
This should fetch all values from the DB with DOB format as mm/dd/yy.
PS: The North Remembers
QUESTION
Working with strings in C, strcat and the strange behavior of terminating null! (#beginner)
Asked 2021-Jun-04 at 10:06I'm coming over from PHP, Ruby and JavaScript programming and I'm really finding my self at loss with C language, and in particular, regarding manipulating strings.
Getting to the bottom of it, I want to get an input from the user and store a text file with that name; However, everything happens but that. To be exact, as far as I could figure it out on my own, it is the terminating null that translates into � character.
Here is a standalone bug example:
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int main()
6{
7 char year[4];
8 scanf("%s", &year);
9 char filename[8] = {};
10 strcat(filename, year);
11 char frmt[4] = ".txt";
12 strcat(filename, frmt);
13 printf("%s", filename);
14 return 0;
15}
16
From my Terminal:
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int main()
6{
7 char year[4];
8 scanf("%s", &year);
9 char filename[8] = {};
10 strcat(filename, year);
11 char frmt[4] = ".txt";
12 strcat(filename, frmt);
13 printf("%s", filename);
14 return 0;
15}
16$ gcc bug.c
17$ ./a.out
182020
192020.txt2020
20
Here is another buggy example:
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int main()
6{
7 char year[4];
8 scanf("%s", &year);
9 char filename[8] = {};
10 strcat(filename, year);
11 char frmt[4] = ".txt";
12 strcat(filename, frmt);
13 printf("%s", filename);
14 return 0;
15}
16$ gcc bug.c
17$ ./a.out
182020
192020.txt2020
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23
24int main()
25{
26 char year[4];
27 scanf("%s", &year);
28 char filename[8];
29 strcat(filename, year);
30 strcat(filename, ".txt");
31 printf("%s", filename);
32 return 0;
33}
34
Here the result is like this: �2020.txt
and the fix is something quite unusual, to my background, at least: changing line 10 to char filename[8] = {};
However, the most strange thing is that this same fix doesn't work over within a broader context of a code: https://vitualizersgit.xyz/teaching/sakile-c/-/blob/master/terminal.c
over there, the exact same code, doesn't even remotely function the same! There the filename
becomes "2020�.txt" which means that strcat
is not overriding the terminating null!
I'm seriously confused!
PS. Thanks in advance!
ANSWER
Answered 2021-Jun-04 at 10:06char filename[8];
does not initialize the array, so there is no guarantee that it contains any zero bytes. You must initialize array to zero by using = {}
or = ""
.
Also, 4 bytes is not enough to store ".txt"
or "2020"
. You need 5 bytes so that you can also store the terminator, so char frmt[5] = ".txt";
.
QUESTION
Strange "mouse:over" behavior after changing object attributes (left, top, radius etc.) via numeric input
Asked 2021-Apr-27 at 16:05I am fairly new to JavaScript programming and FabricJS (I've only been learning both of them for about a month now) so please bear with me.
I am trying to use FabricJS to create a user interface which should basically function as described below:
- User creates a new circle object
- User selects the created circle object
- User is able to modify the selected object using the bounding box (as per usual)
- Upon selecting the circle object, a sidebar positioned next to the canvas is updated dynamically with the parameters of the selected object (in this case the X (left), Y (top) and radius parameters). To do this, the user would need to enter the new desired values in the input boxes on the right hand side and click on the "Update" button afterwards.
This is handled by a switch case as such:
1 case 'circle':
2 if (rows <= 1) {
3 //------------------------------PARAMETER VARIABLES-----------------------------------------------------
4 var x = Math.round(activeObj.get("left"));
5 var y = Math.round(activeObj.get("top"));
6 var r = Math.round(activeObj.get("radius"));
7 //------------------------------DYNAMIC PARAMETERS------------------------------------------------------
8 $('#parameter_input_table tbody').append("<tr><td>X</td><td><input type=\"text\" id=\"x_table\" value=\"" + x + "\"></td></tr>");
9 $('#parameter_input_table tbody').append("<tr><td>Y</td><td><input type=\"text\" id=\"y_table\" value=\"" + y + "\"></td></tr>");
10 $('#parameter_input_table tbody').append("<tr><td>R</td><td><input type=\"text\" id=\"r_table\" value=\"" + r + "\"></td></tr>");
11 $('#parameter_input_table tbody').append("<tr><td><button id=\"btn_submit\">Update</button></td></tr>")
12
13 //------------------------------HANDLERS------------------------------------------------------------------
14 //add event listeners for numeric input
15 $('#parameter_input_table tbody tr td input').eq(0).on('input', function() {
16 x = this.value;
17 activeObj.set({
18 left: x
19 });
20 activeObj.setCoords();
21 canvas.requestRenderAll();
22 });
23 $('#parameter_input_table tbody tr td input').eq(1).on('input', function() {
24 y = this.value;
25 activeObj.set({
26 top: y
27 });
28 activeObj.setCoords();
29 canvas.requestRenderAll();
30 });
31 $('#parameter_input_table tbody tr td input').eq(2).on('input', function() {
32 r = this.value;
33 activeObj.set({
34 radius: r
35 });
36 activeObj.setCoords();
37 canvas.requestRenderAll();
38 });
39 $('#parameter_input_table tbody tr #btn_submit').on('click', function() {
40 activeObj.set({
41 left: x,
42 top: y,
43 radius: r
44 });
45 activeObj.setCoords();
46 canvas.discardActiveObject().requestRenderAll();
47 });
48 }
49 break;
50
- Additionally, the user can delete the currently selected object by pressing the "Delete" key on the keyboard.
I have created a working Fiddle where basically all of the aforementioned functions have been implemented.
Fiddle: Changing FabricJS object parameters using numeric input
However, I am running into a strange issue where updating the values via numeric input causes the cursor to change to the move-cursor at the "wrong" place despite having called setCoords() after modifying the object.
Try it for yourself, you'll see what I mean: open the Fiddle, select the default circle, change the values on the right side and click on update. You'd probably see that the cursor is somehow reacting as if the "mouse:over" event is triggered outside of the new circle's supposed bounding box.
Current workaround:
- Drag the object or
- Reselect object, click update
But obviously this is not a good workaround.
I have also tried deleting the activeObject and creating a new object after the Update button with the values saved in x, y and r. Issue still persists.
If anyone could help me with this issue/direct me to an existing discussion (if this issue has already come up before), I would be very grateful.
ANSWER
Answered 2021-Apr-27 at 16:05When using a value from an input you need to use parseInt()
to convert the value from a string to an integer.
1 case 'circle':
2 if (rows <= 1) {
3 //------------------------------PARAMETER VARIABLES-----------------------------------------------------
4 var x = Math.round(activeObj.get("left"));
5 var y = Math.round(activeObj.get("top"));
6 var r = Math.round(activeObj.get("radius"));
7 //------------------------------DYNAMIC PARAMETERS------------------------------------------------------
8 $('#parameter_input_table tbody').append("<tr><td>X</td><td><input type=\"text\" id=\"x_table\" value=\"" + x + "\"></td></tr>");
9 $('#parameter_input_table tbody').append("<tr><td>Y</td><td><input type=\"text\" id=\"y_table\" value=\"" + y + "\"></td></tr>");
10 $('#parameter_input_table tbody').append("<tr><td>R</td><td><input type=\"text\" id=\"r_table\" value=\"" + r + "\"></td></tr>");
11 $('#parameter_input_table tbody').append("<tr><td><button id=\"btn_submit\">Update</button></td></tr>")
12
13 //------------------------------HANDLERS------------------------------------------------------------------
14 //add event listeners for numeric input
15 $('#parameter_input_table tbody tr td input').eq(0).on('input', function() {
16 x = this.value;
17 activeObj.set({
18 left: x
19 });
20 activeObj.setCoords();
21 canvas.requestRenderAll();
22 });
23 $('#parameter_input_table tbody tr td input').eq(1).on('input', function() {
24 y = this.value;
25 activeObj.set({
26 top: y
27 });
28 activeObj.setCoords();
29 canvas.requestRenderAll();
30 });
31 $('#parameter_input_table tbody tr td input').eq(2).on('input', function() {
32 r = this.value;
33 activeObj.set({
34 radius: r
35 });
36 activeObj.setCoords();
37 canvas.requestRenderAll();
38 });
39 $('#parameter_input_table tbody tr #btn_submit').on('click', function() {
40 activeObj.set({
41 left: x,
42 top: y,
43 radius: r
44 });
45 activeObj.setCoords();
46 canvas.discardActiveObject().requestRenderAll();
47 });
48 }
49 break;
50x = parseInt(this.value);
51activeObj.set({
52 left: x
53});
54
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Script Programming
Tutorials and Learning Resources are not available at this moment for Script Programming