/r/learnjavascript
This subreddit is for anyone who wants to learn JavaScript or help others do so.
Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend.
This subreddit is a place for people to learn JavaScript together. Everyone should feel comfortable asking any and all JavaScript questions they have here.
With a nod to practicality, questions and posts about HTML, CSS, and web developer tools are also encouraged.
No Self-Promotion. The following are not allowed: Requests for subscribers, asking for "test users" for your new JS course, offering paid mentorships, and/or premium courses. Even if there is a coupon discount, no. If you're in doubt, message the mods first.
Good Titles - Write a descriptive title. Titles that begin with "hey guys" will be removed.
Related Subreddits
If you want to post something self-promotional, please message the mods first. Personal blog posts that are relevant to the subreddit's stated subject matter don't need prior approval (and are encouraged!).
/r/learnjavascript
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>ASCII Fire Animation with JavaScript</title>
<meta name="author" content="Thiemo Mättig">
<style type="text/css">
body,
table,
td,
pre {
border-spacing: 0;
margin: 0;
padding: 0;
}
body{
background: #000;
color: red;
height: 100%;
width: 100%;
}
pre {
font-weight:600 ;
}
an {
color: red ;
}
an:hover {
color: #FF0;
}
address {
background: #000;
bottom: 10px;
font-family: Georgia, serif;
font-style: normal;
position: absolute;
right: 10px;
text-align: right;
}
</style>
</head>
<body>
<center style="height: 100%;">
<table height="100%">
<tbody>
<tr>
<td>
<pre>This animated fire in plain ASCII art needs JavaScript to run in your web browser.</pre>
</td>
</tr>
</tbody>
</table>
</center>
<script type="text/javascript">
var size = 80 * 25;
var b = [];
for (i = 0; i < size + 81; i++)
b[i] = 0;
var char = " .:*sS#$".split("");
var e = document.getElementsByTagName("PRE")[0].firstChild;
function f()
{
for (i = 0; i < 10; i++)
b[Math.floor(Math.random() * 80) + 80 * 24] = 70;
an = "";
for (i = 0; i < size; i++)
{
b[i] = Math.floor((b[i] + b[i + 1] + b[i + 80] + b[i + 81]) / 4);
an += char[b[i] > 7 ? 7 : b[i]];
if (i % 80 > 78)
an += "\r\n";
}
e.data = an;
setTimeout(f, 100);
}
f();
</script>
<script type="text/javascript">
var M = document.getelementsbytagname("pre");
var e2 = document.getElementsByTagName("an")
function getRandomColor()
{
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
e2.style.color = color ;
settimeout(getrandomcolor, 100);
}
getrandomcolor();
</script>
I'm importing my Gradle project into eclipse and this is the error I keep getting
Any help is greatly appreciated.
This looks like a Firefox bug to me. Firefox Nightly 134. Downloaded today.
Consider the question here Displaying the content from JSON file on the HTML page.
My initial answer would be to utilize Import Attributes to get the JSON using static import
.
I tested on Chromium 133 and Firefox 134. Firefox 134 throws when static import
is used
<script type="module">
import data from "./data.json" with {type: "json"};
console.log(data);
// ...
</script>
Uncaught SyntaxError: import assertions are not currently supported data.html:7:38
Chromium 133 supports Import Attributes so doen't throw.
So, I began creating a try..catch
trap to use fetch()
and Response.json()
in finally
if `data is not defined when we get there.
Firefox Nightly 134 throws SyntaxError
, and never reaches catch
or finally
, instead we get a SyntaxError
Uncaught SyntaxError: missing ) after argument list
<h1>test</h1>
<script type="module">
/*
import data from "./data.json" with {type: "json"};
console.log(data);
*/
const h1 = document.querySelector("h1");
const json = "./data.json";
let data = void 0;
try {
({ default: data } = await import(json, { with: { type: "json" } }));
h1.textContent = data.header;
} catch (e) {
console.log(e.message);
data = await (await fetch(json)).json();
} finally {
if (data !== undefined) {
h1.textContent = data.header;
}
}
</script>
Now, let's make sure Firefox is really ignoring catch
and finally
blocks by throw
ing an Error
before we get to the dynamic import()
in the code
<h1>test</h1>
<script type="module">
/*
import data from "./data.json" with {type: "json"};
console.log(data);
*/
const h1 = document.querySelector("h1");
const json = "./data.json";
let data = void 0;
try {
throw new Error(`User defined error.`
+ `Firefox Nightly instead throws Uncaught SyntaxError: missing ) after argument list`
+ `for the code below, where Import Attributes are not defined`);
({ default: data } = await import(json, { with: { type: "json" } }));
h1.textContent = data.header;
} catch (e) {
console.log(e.message);
data = await (await fetch(json)).json();
} finally {
if (data !== undefined) {
h1.textContent = data.header;
}
}
</script>
We still get the Uncaught SyntaxError: missing ) after argument list
error logged in DevTools, and we still never reach the catch
and finally
blocks.
Does anybody have a better explanation other than this just being a Firefox Nightly bug why the code never reaches catch
and finally
blocks, even when we explicitly throw
before reaching the unsupported Import Attribute usage in the dynamic import()
on the next line?
I'm using AJAX to retrieve data from a MySQL Database and create a table. In the end column of the table, I want a series of buttons, to carry out different actions for that record (the same actions, using the same set of functions, just with a different record).
What I've tried is:
for (var line of liveFeedJSON) {
//Create <tr> and <tds>
tscButton = document.createElement('button');
tscButton.innerHTML = '<span class="fa-solid fa-keyboard">';
tscButton.className = 'actionButton';
tscButton.onclick = function() {checkAction(this, currentUser, line['svcID'], 'shtTSC', 'System updated.');};
functionsCell.appendChild(tscButton);
}
The trouble is, it seems to pass the arguments from the last line created, whichever button is clicked on and I can't work out how to get round this. Any ideas would be very welcome!
Thanks
Chris
I want to change the title of my HTML page by changing the JSON file
JSON:
{"header": "Hello"}
HTML page:
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="GetData()">
<h1 >test</h1>
<script type="text/JavaScript" src="./script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="GetData()">
<h1 >test</h1>
<script type="text/JavaScript" src="./script.js"></script>
</body>
</html>
JS code:
function GetData() {
// let data = require('./api.json');
let heading1 = document.querySelector('h1');
heading1.textContent = 'data.header';
}
When i run this i see "data.header" on my page. But when i uncomment the 2nd line my script stops working even if i dont remove the quotes.
JS can see the JSON because i can add the console.log(data.header)
and see the result
Can someone give an advice how to fix this and sorry for bad english
Hi Reddit,
I'm working on a project involving Bayer matrix dithering and need some help fine-tuning a function. My goal is to use a dynamic Bayer matrix (of any width or height) to apply dithering to an image while ensuring the final pixel colors are chosen from a predefined palette of RGB values (palArr
).
Here’s what I’m trying to achieve:
Dynamically handle Bayer matrices of varying dimensions (e.g., 2x2
, 4x4
, etc.). Map the pixel colors to the closest color in palArr
. Ensure the dithering effect aligns with the thresholds defined in the Bayer matrix. Here’s an example of one of my functions that isn’t working as expected:
function brayerDithering(context, w, h, ditherMatrix) {
const [matrixWidth, matrixHeight, max] = [
ditherMatrix[0].length,
ditherMatrix.length,
Math.max(...ditherMatrix.flat())
];
const palArr = removedisabledColors(hexToRgb(colors), enabledColorsList);
const imgData = context.getImageData(0, 0, w, h);
const data = ;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const index = (y * w + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
const threshold = ditherMatrix[y % matrixHeight][x % matrixWidth] / max;
const adjustedR = Math.min(Math.max(r / 255 + threshold - 0.5, 0), 1) * 255;
const adjustedG = Math.min(Math.max(g / 255 + threshold - 0.5, 0), 1) * 255;
const adjustedB = Math.min(Math.max(b / 255 + threshold - 0.5, 0), 1) * 255;
const newPixel = findClosest([adjustedR, adjustedG, adjustedB], palArr);
data[index] = newPixel[0];
data[index + 1] = newPixel[1];
data[index + 2] = newPixel[2];
}
}
context.putImageData(imgData, 0, 0);
}
However, the dithering effect doesn’t align with the Bayer matrix correctly, and the chosen colors don’t always seem to match the palette (palArr
) properly.
Wat to do with javascript. If I don't wanna build websites
I have heard great things about the book , The Tour of C++. I know the versions of JavaScript keeps changing but is there a great book I can pickup, read and learn the language and appreciate it more in the process. Expecting some great answers from the experts here :)
Hey I'm still getting the hang of functions, could someone tell me why the total function returns 250 as it should be 143.75, I first tried it with an arrow function as it looked better but I was receiving the same result after changing the function type.
let
bill;
function
calcTip (
bill
){
if (bill >= 50 && bill <= 300) {
return (`${bill * .15}`);
} else {
return (`${bill * .20}`);
}};
const
bill1 = calcTip(125);
const
bill2 = calcTip(555);
const
bill3 = calcTip(44);
function
total(
bill
,
calcTip
) {
return (bill + calcTip); }
console.log(total(125, 125));
const
bills = [bill1, bill2, bill3];
console.log(bills);
pretty sure its gonna be a dumb fix that I should already know, I appreciate the insight guys!
p.s. this started as a class assignment and I felt like taking it a little further.
Hi everyone,
I’m a beginner in JavaScript and web development, and I’m really passionate about this field. I haven't studied computer science formally, but I’ve taken a course to learn HTML, CSS, and JavaScript basics. However, I feel that I lack a deep understanding of JavaScript and struggle with some concepts.
Here’s what I currently know:
JavaScript basics – I can work with functions, loops, and arrays but find complex data manipulation tricky.
NPM and Packages – I can use packages with the help of documentation.
React – I’ve made small frontend and backend projects using React, React Query, and React Router DOM.
Backend – I have some experience with Mongoose and Prisma for databases.
APIs – I’ve built projects like a story generator using AI APIs like Gemini and created image-based story apps.
Challenges I face:
I forget things easily; even though I’ve learned them, I can’t explain them well.
Loops and data manipulation are still difficult for me.
I don’t know TypeScript yet.
What I’m doing now:
Solving problems on CodeChef to improve logic.
My goal:
I want to improve my skills and get a job in web development.
Questions:
What should I focus on to improve my JavaScript skills?
Are there resources you recommend for mastering concepts like loops and data manipulation?
How important is TypeScript, and when should I learn it?
Thank you for your help!
Hello everyone, I am a mid Javascript developer. I have been MEAN/MERN stack developer for 4 years.
I am not an expert at anything. I want to become a pro, enough to make npm packages or fix bugs in packages. Are there any books or any other way I can become such?
My goal is to join one of the FAANG companies so I am trying to improve my skill. If anyone can share a pathway, that will be great. Thank you.
Hello everyone, I am a mid Javascript developer. I have been MEAN/MERN stack developer for 4 years.
I am not an expert at anything. I want to become a pro, enough to make npm packages or fix bugs in packages. Are there any books or any other way I can become such? My goal is to join one of the FAANG companies so I am trying to improve my skill. If anyone can share a pathway, that will be great. Thank you.
What programs, or apps, or websites can be used to experiment with writing JavaScript code? I know the advice is to just jump in and start creating, but where do we jump?
Also, where can I find code to study/modify so I know what works and doesn't? Would that be GitHub or?
Hi guys I am new in web development and I would like to improve my problem solving skill. Is there any books or website can help with it apart from codewar/ leetcode?
HI! I know javascript and nodejs, python well (and even though css and html are not bad languages) I started to create my own social media not to earn money or anything else but for fun. I had added a profile card, home login and signup and a chat but honestly, even if it worked, it wasn't great. Let's get to the point: are there any projects with the basics of a social network on github that can be modified using the code to my liking?
Hey guys, I just completed html, css and completed 10+ landing pages and now I wanna learn JavaScript, and only have access online like YouTube, so who is the best to learn from free of cost ? JavaScript from scratch to advanced and in depth explanation of concept and with project practice? Is codewithharry good ? Sheriyans coding school?
Where do I start?
Hi everyone, so I started learning js full-time a few months ago and have already made a couple of simple apps. Everything was going fine and JavaScript was coming naturally to me without much effort. But as I progressed, I started realising my scripts were incredibly long and maybe not ideally organised. So I gave modules a shot. Worst experience of my life as nothing seemed to work, specially eventlistners. I decide I would try to organise things in objects instead. The problem I’m facing is that, everything seems much harder to do. Again, specially eventlisteners. For one I can’t write html onclick attributes on the DOM as they trigger themselves automatically. Wrapping them in arrow functions doesn’t work either most of the time. EventListeners go bezerk too. Most of the times, through brute force I can make things work and find workarounds but it just seems to be so much more complicated and painful when before it was a breeze. Is this normal? Am I missing something? What’s the point of object oriented programming? Do developers enjoy to suffer? Thanks
Edit: many people have asked for the code, i find this pointless because it's not a specific problem, it's something that happens everytime with eventlistners and methods. Here's the git repo https://github.com/thatideadude/NewLibrary, on line 338 of the index.js there's an eventlistner set to the click of an image that will trigger itself and the method on the line right after before the images even load. This can be confirmed here https://thatideadude.github.io/NewLibrary/ by adding a new book on the bottom right corner. After inputing the author and book name, it will suggest a cover but if you check the console, two messages have been printed proving that the eventlistener run it self automatically. Thanks
Trying to create a 30 second timer on each question for a qualtrics survey. My current issues are that the timer doesnt disappear from question to question, so more than one timers show at the same time, and that the survey doesnt automatically proceed to the next question when the time = 0.
Qualtrics.SurveyEngine.addOnload(function () { // Check if a timer already exists and remove it to prevent duplication var existingTimer = document.getElementById("header_container"); if (existingTimer) { existingTimer.remove(); }
// Create the header container for the timer var headerCont = document.createElement("div"); headerCont.className = "header-cont"; headerCont.id = "header_container";
var header = document.createElement("div"); header.className = "header"; header.id = "header_1";
var timer = document.createElement("div"); timer.className = "timer"; timer.id = "timer_1"; timer.innerHTML = "Time Remaining: <span id='time'>00:30</span>";
headerCont.appendChild(header); header.appendChild(timer);
// Insert the timer at the top of the page document.body.insertBefore(headerCont, document.body.firstChild);
// Variable to store the interval ID let timerInterval;
// Function to start the timer function startTimer(duration, display) { var timer = duration, minutes, seconds; timerInterval = setInterval(function () { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) { clearInterval(timerInterval); timeOver(); } }, 1000); }
// Function to execute when time runs out function timeOver() { document.getElementById("timer_1").innerHTML = "Your time has run out!"; Qualtrics.SurveyEngine.setEmbeddedData("blockTimeFlag", "1"); // Trigger the Next button to move to the next question setTimeout(() => jQuery("#NextButton").trigger("click"), 500); }
// Add event listener to the Next button to clear the timer jQuery("#NextButton").on("click", function () { if (timerInterval) { clearInterval(timerInterval); } });
// Start the timer var timerSeconds = 30, display = document.querySelector('#time'); startTimer(timerSeconds, display); });
Qualtrics.SurveyEngine.addOnUnload(function () { // Clear the timer interval when leaving the page var timerInterval = Qualtrics.SurveyEngine.getEmbeddedData("timerInterval"); if (timerInterval) { clearInterval(timerInterval); }
// Remove the timer element from the DOM to ensure it does not carry over var headerContainer = document.getElementById("header_container"); if (headerContainer) { headerContainer.parentNode.removeChild(headerContainer); } });
Hi, I was just trying to remove EventListeners in a Userscript (Tampermonkey, meaning I have no control over their creation in the first place). First I was using getEventListeners to some success not realizing that this is a browser console feature. Interesting enough, I could extract the references and remove most Events that way, but apparently you can't remove Listeners that were created through a <script> tag (bug?).
Since getEventListeners isn't an option outside of debugging, I thought I could use a solution someone suggested on stackoverflow, by wrapping the default addEventListener method. This seems to only partially work. I'm assuming it either fails to track most events, because the userscript doesn't inject fast enough or the element.addEventListener()
function doesn't cover all ways to add Event Listener.
Is there really no straightforward way to manipulate the events of websites (userscript, addon)?
The only solution I can think of is parsing the whole website and trying to replace every call with your own (or writing your own js engine that actually keeps track of all Listener). I feel like the user should be in control, but there are no browser features that effectively prevent js features like history manipulation (redirects), debugger, overwriting default events (e.g. right clicking) etc.
Hi all,
I'm trying to work with the Claude API in Javascript.
I've gotten it to correct return a response. In the console, I see the response content:
{stop_sequence=null, role=assistant, type=message, content=[{type=text, text=Hello! How can I assist you today? Feel free to ask me any questions or let me know if there's anything I can help you with.}], id=msg_01APkyVu4UJGGd1bVchY1bTY, stop_reason=end_turn, usage={input_tokens=9.0, output_tokens=33.0}, model=claude-3-5-sonnet-20240620}
How do I parse the content
value into just the response text?
My code is returning an array size of 1 when it should be 4. Any clues as to why?
let groceryList = [];
// Wait until DOM is loaded
window.addEventListener("DOMContentLoaded", function() {
document.querySelector("#addBtn").addEventListener("click", addBtnClick);
document.querySelector("#clearBtn").addEventListener("click", clearBtnClick);
// Load the grocery list from localStorage
let tempList = loadList();
if (tempList) {
groceryList = tempList;
}
if (groceryList.length > 0) {
// Display list
for (let item of groceryList) {
showItem(item);
}
}
else {
// No list to display
enableClearButton(false);
}
});
// Enable or disable the Clear button
function enableClearButton(enabled) {
document.querySelector("#clearBtn").disabled = !enabled;
}
// Show item at end of the ordered list
function showItem(item) {
let list = document.querySelector("ol");
list.innerHTML += `<li>${item}</li>`;
}
// Add item to grocery list
function addBtnClick() {
let itemTextInput = document.querySelector("#item");
let item = itemTextInput.value.trim();
if (item.length > 0) {
enableClearButton(true);
showItem(item);
groceryList.push(item);
// Save groceryList to localStorage
saveList(groceryList);
}
// Clear input and add focus
itemTextInput.value = "";
itemTextInput.focus();
}
// Clear the list
function clearBtnClick() {
enableClearButton(false);
groceryList = [];
let list = document.querySelector("ol");
list.innerHTML = "";
// Remove the grocery list from localStorage
clearList();
}
function loadList() {
let listString = localStorage.getItem('list');
if (listString) {
return listString.split(', ');
} else {
return [];
}
}
function saveList(groceryList) {
let listString = groceryList.join(',');
localStorage.setItem('list', listString);
}
function clearList() {
localStorage.clear();
}
Hi! I’m a student currently studying Cybersecurity on my first year at Kristiania Høyskole i Norway.
I have an assignment in Javacript in which I desperatly need help, and I was wondering if anyone could help me?
My brain is kinda slow so all these concepts are kind of confusing, but I know the basics. I’m desperate to the point where I guess I’d be willing to pay, but I can’t give too much. Anything would be appreciated 😀
EDIT: I have recieved help. Thank you!
Hello, anyone can explain to me why an element that has a transition of being transformed from translateX(-100%)
to translateX(0%)
and is being observed by the intersection observer API causes problems such as the observer API getting called back and forth when the element is intersecting.
HI there Im just a bit stuck on a project, I need to remove a line by id on a txt document through a console on eclipse. Im a bit new to this part of js.
I wanted to create an animated video using frame images instead of importing a video element, because it is way smoother that way. I found a couple of ways to do this using vanilla JS and also GSAP
Almost all of the examples I found online use the same set of images, which is fine but when I try to use my own local images and restructure the code to fit my image size and frame rate the images won’t show up. On chrome, all I get is “Not allowed to load local resource”. How do I get the code to work on local images?
I know some JS, node, express or python.
I am going to make singleplayer autobattler browser game. I made things work but as it is supposed to be a browser game I want to make things as light as posible and I am looking for some blueprints/examples.
Also some guide on frontend?
I know some JS, node, express or python.
I am going to make singleplayer autobattler browser game. I made things work but as it is supposed to be a browser game I want to make things as light as posible and I am looking for some blueprints/examples.
Also some guide on frontend?
Hi all, I’m creating a custom gantt chart widget for SAP analytics cloud, I need some help to get some functionalities working, like addDimension/removeDimension dynamically and grouping/tree structure. Please help/ping me. My code is generic and I’ll share, please help me modify it. My knowledge in JS is likely less than 10%. :(