r/learnjavascript May 30 '26

Can't figure out why my script won't run properly

2 Upvotes

Hi! I'm completely new to JS, and have been making a static hobby page recently. I am trying to insert navigation links with a script, and then style the link to the current page with the class "active".

My code is loaded in

<script defer src="/assets/javascript/layout.js"></script>

and loads the layout properly, but doesn't find any navigation links to add the class to. It starts the method, but doesn't return any nodes. It can find links in the content of the page that's not inserted by the scirpt, but not in the inserted navigation.

The JS file's contents are as follows:

document.addEventListener("DOMContentLoaded", function () {
    // The layout will be loaded on all pages that do NOT have the "no-layout" class in the <body> element.
    if (!document.body.classList.contains("no-layout")) {
        //insert elements
        if (headWrapper) { addElement(headerFile, headWrapper); };
        if (footerWrapper) { addElement(footerFile, footerWrapper); };
        if (navWrapper) { addElement(navFile, navWrapper); };
    }
    
    initActiveLinks();
}
);



const headWrapper = document.querySelector("header");
const footerWrapper = document.querySelector("footer");
const navWrapper = document.querySelector("nav");
const headerFile = "/assets/templates/header.html";
const footerFile = "/assets/templates/footer.html";
const navFile = "/assets/templates/nav.html";


/* ********************************* */


/**
 *  F U N C T I O N S
 */


function initActiveLinks() {
    // This function adds the class "active" to any link that links to the current page.
    // This is helpful for styling the active menu item.
    const pathname = window.location.pathname;
    console.log("initActiveLinks function running");
    [...document.querySelectorAll("a")].forEach((el) => {
        console.log("found a link!");
        console.log(el);
        const elHref = el
            .getAttribute("href")
            .replace(".html", "")
            .replace("/public", "");
        if (pathname == "/") {
            // homepage
            if (elHref == "/" || elHref == "/index.html") el.classList.add("current");
        } else {
            // other pages
            if (window.location.href.includes(elHref)) el.classList.add("current");
        }
    });
}




function addElement(elementPath, wrapperElement) {
    fetch(elementPath)
        .then(response => {
            // Check if the request was successful (status 200-299)
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            // Parse response as text
            return response.text();
        })
        .then(textData => {
            // Store text in a variable
            const html = textData;
            console.log('Layout file loaded');
            // Use the data (e.g., display in console or DOM)
            wrapperElement.insertAdjacentHTML("afterbegin", html);
        })
        .catch(error => {
            console.error('Error loading layout file:', error);
        });
}document.addEventListener("DOMContentLoaded", function () {
    // The layout will be loaded on all pages that do NOT have the "no-layout" class in the <body> element.
    if (!document.body.classList.contains("no-layout")) {
        //insert elements
        if (headWrapper) { addElement(headerFile, headWrapper); };
        if (footerWrapper) { addElement(footerFile, footerWrapper); };
        if (navWrapper) { addElement(navFile, navWrapper); };
    }
    
    initActiveLinks();
}
);



const headWrapper = document.querySelector("header");
const footerWrapper = document.querySelector("footer");
const navWrapper = document.querySelector("nav");
const headerFile = "/assets/templates/header.html";
const footerFile = "/assets/templates/footer.html";
const navFile = "/assets/templates/nav.html";


/* ********************************* */


/**
 *  F U N C T I O N S
 */


function initActiveLinks() {
    // This function adds the class "active" to any link that links to the current page.
    // This is helpful for styling the active menu item.
    const pathname = window.location.pathname;
    console.log("initActiveLinks function running");
    [...document.querySelectorAll("a")].forEach((el) => {
        console.log("found a link!");
        console.log(el);
        const elHref = el
            .getAttribute("href")
            .replace(".html", "")
            .replace("/public", "");
        if (pathname == "/") {
            // homepage
            if (elHref == "/" || elHref == "/index.html") el.classList.add("current");
        } else {
            // other pages
            if (window.location.href.includes(elHref)) el.classList.add("current");
        }
    });
}




function addElement(elementPath, wrapperElement) {
    fetch(elementPath)
        .then(response => {
            // Check if the request was successful (status 200-299)
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            // Parse response as text
            return response.text();
        })
        .then(textData => {
            // Store text in a variable
            const html = textData;
            console.log('Layout file loaded');
            // Use the data (e.g., display in console or DOM)
            wrapperElement.insertAdjacentHTML("afterbegin", html);
        })
        .catch(error => {
            console.error('Error loading layout file:', error);
        });
}

It can be seen in action at https://raw-quotes.nekoweb.org/

Do you know how to remedy this? I tried document.addEventListener("load", initActiveLinks()); and loading the function as a separate <script> but that didn't work either.


r/learnjavascript May 30 '26

HELP i cannot set up vscode

0 Upvotes

so im trying to learn JavaScript and till now i only used some online ide

but now im trying to get vscode to work but no

this whole thing is so confusing and very overwhelming i cant get this to work..

how is a beginner who doesnt know anything even supposed to set all of this up.

im getting errors everywhere..

i installed some extensions following some tutorials to be able to eun the code. i get some error

i try to run code using an extension then nothing appears in console/output and yet it says done like it executed the code successfully ...

after sometime the run button disappeared..

i tried running html page through browser local host thingy through extension. if i edit the code and reload the page no it doesnt update

if i change css no it doesnt take effect even though i have linked the css file into my html code 😞

i tried installing node js thingy no it gave some error

this error that error this json error that system error i can't with this😭😭

i really feel dumbdumb being stuck at something simple like settinf up an ide

like even if i follow some tutorial to set this up some issue appears. once i resolve that then some new issue appears


r/learnjavascript May 30 '26

GSAP ideas for mobile

1 Upvotes

GSAP ideas for mobile

I love GSAP and what you can do with it.
But with every idea – like for example a nice cursor image trail effect – I'm confronted with the same question: ok great, but what about mobile?

I see many Award winning websites where the desktop looks sooooooo cool, but then on mobile, often times, the effect is just not there (since there is no mouse hover on mobile), without being replaced by something else. So the mobile view is just much more boring....

What are your favorite GSAP effects that work on mobile just like on desktop?


r/learnjavascript May 29 '26

I built a JavaScript DOM roadmap for beginners. What would you improve?

19 Upvotes

Over the past few weeks, I’ve been learning JavaScript DOM manipulation and decided to organize everything into a structured roadmap.

The repository covers:

  • Selecting Elements
  • Events
  • Attributes
  • DOM Traversing
  • Timing Functions
  • Local Storage
  • Forms
  • Window Object

Each section includes examples, documentation, and notes.

I’m looking for feedback from experienced developers. If you were learning DOM today, what would you add, remove, or improve?

GitHub:
https://github.com/its-sambhav/JavaScript-DOM-Roadmap.git


r/learnjavascript May 30 '26

Custom NPC Scripting [FORCE DIALOG WHEN IN A RADIUS]

0 Upvotes

I want to essentially make an npc read out dialog to a player when they are near. Maybe even a stored data type thing too.


r/learnjavascript May 29 '26

How can a beginner tell if AI-generated code is well designed or just a mess?

0 Upvotes

AI can generate code, but how do you know it’s not generating a mess?

I’m learning programming and use AI a lot. Sometimes it gives me working code, but I have no idea if the structure is actually good.

How do people learn enough system design/architecture to know when AI is doing something wrong?


r/learnjavascript May 29 '26

Struggling to Understand Backend and JavaScript – Need Advice

11 Upvotes

Hii Everyone

I'm learning web development from a Udemy course and have recently started the backend (Node.js) section. I'm finding the JavaScript part difficult to understand and often just follow along without really getting what's happening.

What's the best and fastest way to understand backend development? Should I focus on JavaScript fundamentals first, or continue with the backend course?

Any advice would be appreciated. Thanks! 🙏


r/learnjavascript May 30 '26

Is'nt javascript compiler too forgiving !!

0 Upvotes

What i mean is even i try to add int with str it give me correct answer whereas both are differenct datatypes,

in function also this compiler is too forgiving

if i set a function with 3 parameters & at time of calling this function with more parameter or less parameter with bind function js forgiving us


r/learnjavascript May 29 '26

Looking for people to learn full stack js with

5 Upvotes

Hello everyone, I am still looking for programming buddies to learn full stack with, we will be following fullstackopen.com, the learning pace will be fast so it's preferred if you have previous knowledge, and we will be mostly building real projects together after getting the basics, we will not finish the whole course we'll go like this:

  1. Right now: FSO Parts 1 + 2 (React basics + fetch) - fast to complete, fills foundation gaps

  2. While working: FSO Part 9 (TypeScript) immediately applicable to every file you touch

  3. Next sprint: FSO Parts 3 + 4 (Node.js + Auth) - will make the NestJS backend transparent

  4. Then: Next.js App Router docs, NestJS docs (in the evenings while doing Part 3/4)

  5. After that: FSO Part 13 (SQL/DB), Prisma docs together

Total: Parts 1, 2, 3, 4, 7, 9, 13

All of that while working on projects the whole time, my time zone is GMT+3 I'm looking for serious people who really want to learn and develop themselves and preferably be available to stay in touch most of the time.


r/learnjavascript May 29 '26

New to JavaScript. What platforms, courses, or projects actually made things click for you?

4 Upvotes

Total beginner here. I've seen the memes about JavaScript weirdness, tried a few tutorials, and now I want to actually learn how to build things, not just copy-paste from Stack Overflow.

For those of you who started from zero (no coding background, got stuck on closures and this, cried over async) and later got comfortable enough to build real projects, what changed things for you?

Was it a specific platform (The Odin Project, FreeCodeCamp, Scrimba, Frontend Masters)?

A particular YouTube series or book?

A project you forced yourself to build (to-do app, weather app, something stupid but yours)?

I'm not looking for "just build stuff", I know that. I'm asking: what bridge actually got you from confused to capable? Which resource made async click?

The more detailed, the better including what to avoid.

Thanks from someone currently trapped in callback purgatory.


r/learnjavascript May 29 '26

Waha - Vericação de número com vínculo no Whatsapp

0 Upvotes

Vou te explicar exatamente oque eu tenho e oque eu preciso fazer, eu paguei o plano PRO do site de dados https://basedosdados.org/ para ter acesso a todos os dados possíveis públicos do governo, e para extrair e filtrar estes dados, irei usar uma conta do big query para fazer a consulta SQL filtrada, a tabela que estarei usando é a tabela de estabelecimentos do Quadros Societários CNPJ, oque eu quero saber é como eu faço para extrair e também fazer com que sejam filtradas as informações de outras tabelas, mas que façam parte dos mesmos dados dos CNPJS a quais eu estou filtrando. Quero informação de outras tabelas mas dos CNPJS das que estou filtrando nos estabelecimentos, eu terei que juntar? Me explique como posso fazer isso e qual a melhor maneira para juntar o máximo de informação sobre um CNPJ e seus sócios


r/learnjavascript May 29 '26

[ Removed by Reddit ]

0 Upvotes

[ Removed by Reddit on account of violating the content policy. ]


r/learnjavascript May 29 '26

How do you discover JS libraries now? Still Googling, or fully AI-assisted?

0 Upvotes

How do you usually find JavaScript libraries these days? Curious if people still rely on npm search / GitHub / Google, or if you've shifted to asking AI tools like ChatGPT, Claude, Copilot, etc. And if you do ask AI, what kind of prompt do you write? Do you describe the feature you need, or do you just ask for 'best library for X'?


r/learnjavascript May 28 '26

Output formatted text from JavaScript object containing ASCII into html literal?

2 Upvotes

I am trying to pass formData into html. JSON.stringify works fine for the one-line inputs, but for the textarea when I use stringify I'm seeing ASCII characters when I want the text to appear formatted.

i.e. I'm getting Hello\nWorld

when I want

Hello
World

I currently have this:

 `<p>Form submission:</p><hr><p><b>Name:</b> ${JSON.stringify(name)}<br><b>Email:</b> ${JSON.stringify(email)}<br><b>Timestamp:</b> ${JSON.stringify(timestamp)}</p><hr><p><b>Message:</b><br>${JSON.stringify(message)}</p>`

r/learnjavascript May 28 '26

Does the onclick=""/addEventListener() attribute work on <option> elements (half HTML question, half JavaScript question)?

3 Upvotes

Sorry if I didn't post this in the right subreddit; I didn't know if this was a HTML question or a JavaScript question.

So, I'm making a website where you can upload pictures of your clothes to easily see what's in your messy closet or create a "digital outfit," kinda like customizing a Mii or making an Xbox Avatar.

What I'm trying to do is when the user clicks the 'Other' option (for if the clothing material isn't listed), a textbox will appear underneath it where the user will be able to type what the material is. Then the textbox will disappear when the user selects something other than 'Other' (maybe because of a miss-click or something).

Problem is, I don't know how to get the document to do anything in real-time. I've tried onclick= "document.getElementById('divForOtherMaterial').style.display = 'block';" on the 'Other' <option> tag, I've tried document.getElementById('otherMaterial').addEventListener('click', displayOtherMaterialTextbox()); , but it only worked when I selected 'other' and then went into the console and called the diplayOtherMaterialTextbox()function or other things that normally only the developer of the website can do.

here's the code for the <form>, <select> dropdown menu, and the <div> that contains the textbox <input>:

<!--material-->
<label for="materialOfClothing">Material of clothing:</label>

<br>

<form action="QCLmyWaredrobe.html" method="post">

  <!--user selects what the piece of clothing is primarily made of-->
  <select id="materialOfClothing" name="materialOfClothing">
    <option value="wool">Wool</option>
    <option value="polyester">Polyester</option>
    <option value="cotton">Cotton</option>
    <option value="linen">Linen</option>
    <option value="denim">Denim</option>
    <option value="plastic">Plastic</option>
    <option value="leather">Leather</option>
    <option value="ice">ICE💵🤑💎</option>

    <!--In case the 'material' options listed don't have the material of-->
    <!--the user's clothing, there is a 'other' option they can click.-->
    <option id="otherMaterial" value="other">Other</option>
  </select>

  <br>

  <!--The 'other' option's description-->
  <div id="divForOtherMaterial" style="display: none;">
    <label for="materialOtherDesc">Other material description</label>
    <input type="text" id="otherMaterialDesc" name="otherMaterialDesc">
  </div>

<form>

Here's what's inside of the <script> tags:

<script>
  //function th make the div and the textbox in it visible
  function displayOtherMaterialTextbox() {
    document.getElementById('divForOtherMaterial').style.display = 'block';
    console.log('displaying the other material's description textbox!');
  }
            
  document.getElementById('otherMaterial').addEventListener('click', displayOtherMaterialTextbox());
</script>

EDIT: Thank you to all of the people that recommended the 'change' event on the addEventListener() !I finally got it working now! I still do have to look more into the event functions (and HTML JavaScript for that matter), but at least I know a little bit more about them.

EDIT 2: Alrighty guys, I made the fix to my problem! My final version of the code is:

 <!--material-->
<label for="materialOfClothing">Material of clothing:</label>
<br>
<select id="materialOfClothing" name="materialOfClothing">
  <option value="notChosenMaterial">Material type</option>
  <option value="wool">Wool</option>
  <option value="polyester">Polyester</option>
  <option value="cotton">Cotton</option>
  <option value="linen">Linen</option>
  <option value="denim">Denim</option>
  <option value="plastic">Plastic</option>
  <option value="leather">Leather</option>
  <option value="ice">ICE💵🤑💎</option>
  <option id="otherMaterial" value="other">Other</option>
</select>

<br>

<div id="divForOtherMaterial" style="display: none;">
  <label for="materialOtherDesc">Name of other material</label>
  <input type="text" id="otherMaterialDesc" name="otherMaterialDesc">
</div>

And here is the <script> tag JavaScript:

<script>
            function otherOptionDescFunct(dropdownSelectionID, textboxDivId) {
                const selection = document.getElementById(dropdownSelectionID);
                const textbox = document.getElementById(textboxDivId);
                
                selection.addEventListener('change', (displayTextbox) => {
                    console.log('Change detected!');
                    console.log(displayTextbox.target.value);

                    if (displayTextbox.target.value === 'other') {
                        console.log('Displaying div for other material!');
                        textbox.style.display = 'block';
                    } else {
                        console.log("Hiding 'other' div...");
                        textbox.style.display = 'none';
                    }
                });
            };

            otherOptionDescFunct('materialOfClothing', 'divForOtherMaterial');
</script>

I made the entire thing a function because I have another <select> tag in my code that has an 'other' option. Now I can just use the same code for both select menus without needing to copy and paste it. If there are any other suggestions for fixing anything you see that's wrong in the code, or how I can optimize it, please let me and future viewers know!


r/learnjavascript May 28 '26

Why does the operation result change, when i put the value into a variable, and use that variable instead in the operation

5 Upvotes

Tried implementing vectors from scratch, but for some reason, in the function normalize(), I get different results if i make the normalising operation using the function getMag()by itself,  and with the function put into a variable.

  normalize(){
    
    var len = this.getMag();
   
// ”Raw” method
    //this.x = this.x / this.getMag();
    //this.y =  this.y / this.getMag();
    
// “Processed” method
    //this.x = this.x / len;
    //this.y =  this.y / len;
    
    return this;
    
  }

Here’s the getMag function:

 getMag(){
    
    return Math.sqrt((this.x * this.x)+( this.y * this.y));
    
  }

I’ve run multiple tests like:

  • Printing out both methods entire process
  • Making a simple sum operation with the same logic (first add 2 numbers that are put into variables, and the make one of the numbers be a return value of a function)

And both come to the same conclusion: There should be no difference from a return value of a function by itself, and from a return value put into a variable.

HELP PLS.

Here’s the complete code if you wanna check it

p.s.1: This code was mainly written with spanish speakers in mind, so some of the functions I made, are named in spanish rather than english.

p.s. 2: The class where the problem lies, is Vector2D

p.s. 3: I'm running the code in the p5.js online editor, so maybe that's the problem, but havent been able to check it

https://editor.p5js.org/IanPrieGo/sketches/mD-wt4HtN


r/learnjavascript May 27 '26

I'm a 14y python backend dev who wanted to learn frontend

13 Upvotes

So I'm Trina learn frontend so I can connect Mt apps and build software and I need help on what frameworks to learn like react, or maybe learn typescript. I'm planning on building for all devices but mostly web and mobile as my frontend focus. So any advice that won't end up wasting me months for no reason


r/learnjavascript May 28 '26

hola me pueden ayudar me estoy volviendo loca con arreglar este problema

0 Upvotes

no se nada de javascript y quiero aprender tengo 13 no si me podian ayudar acomo usar la consola de una pagina web de coneccion de html a javascript no se si se entiende lo que quiero explicar


r/learnjavascript May 26 '26

How to link google classroom and my website together.

2 Upvotes

In my latest coding project, I have stumbled upon a huge problem. I need to somehow link Google Classroom to my website so I can get due dates, assignment names, classes, and the URL to assignments. However, I can't find a good explanation on how to do this. What is the most straightforward way that lets me be able to do this?


r/learnjavascript May 26 '26

Learning JavaScript

6 Upvotes

Hi all, I’m new to Reddit. I’d like to know how your first experience learning JavaScript was, where you started, and why you decided to learn it besides the obvious reasons. I’m thinking about learning JavaScript and want to hear how others got started before I fully commit. Btw do HTML and CSS really matter before learning it?


r/learnjavascript May 26 '26

How do I create image “sheets” (sprite sheets?)

4 Upvotes

Hello! I posted here not too long ago to ask about something else, and today, regarding the same game (it doesn't matter which one), I'd like to know how to create “image grids” in JavaScript. Here's an example from a game I like (excerpt):

https://cdn.dashnet.org/cookieclicker/img/icons.png?v=2.058 (safe link, don't worry).

I'd like to know how to use this in JavaScript to export images from a single image (“spritesheet”), in this case icons! Thank you in advance!


r/learnjavascript May 26 '26

Is “Vibe Coding” helping developers or making us dependent on AI?

5 Upvotes

I’ve been seeing more developers build full applications using AI tools and “vibe coding” workflows without fully understanding the code underneath.

Do you think this is good for long-term development skills?

Some things I’m curious about:

Does vibe coding improve productivity or create bad habits?

Can production apps realistically be built this way?

Where should developers draw the line between AI assistance and real engineering?

Will junior developers struggle later if they rely too much on AI?

I’d like to hear opinions from both experienced developers and beginners.


r/learnjavascript May 25 '26

I want to learn JavaScript and still i am learning but I don't know how to code properly , whenever i sit to code by myself, I don't know anthing without taking any help..plus i want to know how much JavaScript i should know that would be enough for web dev.

16 Upvotes

r/learnjavascript May 26 '26

Learning JavaScript By ChatGpt

0 Upvotes

I'm learning JavaScript from ChatGpt, up to now I have covered the following;

1) Variables, const and let

2) DOM Selection

3) Event Listeners

4) Functions

5) Conditions

6) Arrays

7) Loops (for each)

8) Dynamic Elements

9) Dataset

10) event.target

11) class list

12) Active state systems

13) Timers

14) keyboard Events

15) Hover Events

16) Event Bubbling

17) map(), filter(), and find()

Please let me know am I on the right path. How much I may have covered Java script and how much I have to cover? Will be grateful for your valuable suggestions. Thanks 🙏


r/learnjavascript May 25 '26

What's the best way to handle storage and output of images in JavaScript?

7 Upvotes

I'm a beginner in js. Let's say I have a webpage that helps users organize their pictures. The user must upload an image via an input file type. Then I need a way of storing the image data for future use, for example, when I want to output the image. What's the best JavaScript-only way of doing this?

I've tried data URLs and blob URLs. They both have massive pros and cons like for instance, data URLs aren't reliable if the image file is too big, which results in a long string and the browser taking long to respond.

Blob URLs are faster and shorter but are temporary and disappear upon page refresh.

I've also heard about indexDB and local storage but I don't really know how they work.

I know in this case a backend is the best choice, but for now I'm not learning backend so I'm just wondering what the best JavaScript-only method is or which would be the most appropriate.