/r/learnjavascript

Photograph via snooOG

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.


Posting and Commenting Guidelines

  1. Be Welcoming. n00bs are welcome here. Negativity is not.
  2. Include Context. If you’re asking for help, include enough information for others to recreate your problem.
  3. 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.

  4. 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

264,928 Subscribers

1

How to Filter out text

I made this simple code to take an image as an input then displays the image in a frame and then uses OCR to display the text from the image in another frame, now I just want to filter out the text displayed to only show specific words from that text, can anyone help?

here’s the code:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AI Image Text Detection</title><script src="https://cdn.jsdelivr.net/npm/tesseract.js@2.1.1/dist/tesseract.min.js"></script><style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f0f4f8; display: flex; flex-direction: column; align-items: center; margin: 0; padding: 20px; } h1 { color: #333; margin-bottom: 20px; } input\[type="file"\] { margin-bottom: 20px; padding: 10px; border-radius: 8px; border: 1px solid #ccc; background-color: #fff; cursor: pointer; transition: border-color 0.3s; } input\[type="file"\]:hover { border-color: #888; } .container { display: flex; gap: 20px; } .frame { width: 400px; height: 400px; border-radius: 20px; border: 4px solid #0078D4; background-color: #ffffff; display: flex; justify-content: center; align-items: center; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); overflow: hidden; transition: transform 0.3s; } .frame:hover { transform: scale(1.02); } img { max-width: 100%; max-height: 100%; border-radius: 16px; } .text-frame { width: 400px; padding: 20px; border-radius: 20px; border: 4px solid #4CAF50; background-color: #ffffff; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); display: flex; justify-content: center; align-items: center; font-size: 16px; white-space: pre-wrap; color: #333; } </style></head><body><h1>Upload Your Image and Extract Text</h1><input type="file" id="imageInput" accept="image/\*"><div class="container"><div class="frame" id="imageFrame"><p>Image will appear here...</p></div><div class="text-frame" id="textFrame"><p>Detected text will appear here...</p></div></div><script> const imageInput = document.getElementById('imageInput'); const imageFrame = document.getElementById('imageFrame'); const textFrame = document.getElementById('textFrame'); imageInput.addEventListener('change', function() { const file = this.files\[0\]; if (file) { const reader = new FileReader(); reader.onload = function(e) { imageFrame.innerHTML = \`<img src="${e.target.result}" alt="Uploaded Image">\`; // Run OCR on the image Tesseract.recognize( e.target.result, 'eng', { logger: (m) => console.log(m) } ).then(({ data: { text } }) => { textFrame.textContent = text.trim() || 'No text detected.'; }).catch(err => { textFrame.textContent = 'Error in text detection.'; console.error(err); }); } reader.readAsDataURL(file); } }); </script></body></html>
4 Comments
2024/11/10
15:14 UTC

3

Is Doing projects while watching tutorials Okay?

I am doing JS. I want to do some projects. So, I watch tutorials on youtube the try recreate each section but sometimes when I forget what to do I again watch the video and then do. Its kind of copy paste but I do improvise a bit where I feel this should be this. Will i be able to improve like this. I am completely newbie I dont know much that is why I watch Tutorials For projects.....

Your Opinions Would be appreciated.......

9 Comments
2024/11/10
14:22 UTC

2

Surprising Precision with Logs

> let {log} = Math;
undefined
> let factor = 1 / log(2);
undefined
> factor
1.4426950408889634
> factor * log(65536)
16
> 16 === factor * log(65536)
true

I was expecting an approximation, like 16.000000000132 or 15.99999999998 .

3 Comments
2024/11/10
14:17 UTC

4

What exactly makes data "unreachable" for garbage collector?

Hello!

I think I understand the basic concept of it like:

const person = "Bob"
person = null; // If there was nothing like person1 = person2, then there is nothing points to "Bob" anymore and it's removed from the memory

But let's say I want to clear a linked list (with no outside connection like const someVariable = head.next)
// head -> node1 -> node2 -> node3
head.next = null

There is still a link to node2 in node1.
I would guess that since there is no link anywhere that points to node1, it would be considered "unreachable" and cleared, which would make node2 "linkless" and then it's something like domino effect.
But I don't think that my guess is correct.

And then what if it's a double linked list? Then there is no "linkless" nodes to begin. So it's a memory leak then?

I tried to look for the answer and some say that head.next=nullis enough, but some say that correct way is to remove links from each node beforehand.

So what exactly makes data "unreachable" for it to be cleared by garbage collector?

5 Comments
2024/11/10
14:12 UTC

8

How to relearn what I know?

I’m in a University program that has very short deadlines with our Js projects, and I believe they have it mapped out with AI assistance in mind. The lectures arent detailed or relevent enough to teach us all we know for said projects, so we rely on knowledge we mainly obtain ourselves.

I, as well as nearly the entire class, uses Chatgbt/CoPilot for assistance with our coding, as it feels like the only way to survive the 5-6 days we have to make a whole project with our lapse in Js knowledge. Ive become reliant on AI to write my code for me. I understand all the concepts I use, but without AI, I cannot write the code and make it work. I would have issue structuring my code. I would have errors everywhere due to some incorrect syntax here and there.

I understand what I look at, but I can’t write it myself. I’m 1 month into Js. Is this a normal and fine place to be in a modern-coding context? How do I move forward? I have very little time to actually practice code, so it isn’t as easy as going back and relearning everything I know in a literal sense.

15 Comments
2024/11/10
12:25 UTC

1

Trying to make a Compact Jisho.org app using JS/Electron

Hello,

I am looking for some help, I've been trying to make a compact version of Jisho.org for a project I am working on, but I'm not really a programmer or anything like that, so I have no clue what I am doing. I decided to get AI to make the basic structure, and then I have been fiddling on my own to see if I can get it to work, but I've hit a wall. No matter what I do I can't get the app to work as I intend it to, so I was wondering if someone could help me figure out why it is displaying only a white screen. (I'm sure the AI prob messed something up).

The app I am trying to make is meant to be like this. First, a home page which shows the standard jisho.org search bar, so I can search terms which then are listed on the same page. Second, an examples page which pulls data from jisho.org sentence examples for each searched term. Third, a history page that stores all my searched terms for a single day and then deletes them at midnight.

Thank you in advance.

What I have atm (what loads immediately from opening): https://imgur.com/a/sfbNZLn

JishoCompact: https://drive.google.com/file/d/1aWexSTAukQ03yqN20Hg9EdKDC0oBmkD0/view?usp=sharing

0 Comments
2024/11/10
03:07 UTC

0

Testing User Console Input with Vitest

Hey everyone, I'm learning how to use vitest at the moment. I have an application running with Node. The user is asked for an input which they would ordinarily enter into the console. I want to test this by having the test do that. I've tried playing around with mockReturnValue() but that hasn't been successful. Anyone know how to go about doing this?

1 Comment
2024/11/10
02:03 UTC

2

Is this a Chrome bug or is it just me?

Hi -

This is a page that has a button that let's you skip 40 seconds of an audio file (using .currentTime()): https://f004.backblazeb2.com/file/metadaddy-public/onload.html

After testing, I'm seeing a very strange behaviour. The button works for me in Safari - but not in Chrome (using the latest version).

What is even weirder is that when I load the page in Chrome, the skip 40 sec button does not work (just plays the sound from the beginning). But if I close the tab, then right click on the browser and click "Reopen Closed Tab", then click the button it now works?

If I reload the page in this tab, the button still works. But if I close the tab, open a new one, paste/go to the URL and click the button, it does not work again (unless I close it again and "Reopen Closed Tab").......

This is the weirdest bug I've ever come across. Wondering if it has something to do with how Chrome caches stuff / this audio file? Is it a bugged behaviour with .currentTime() and .play()?

Is anyone else experiencing this? Thanks for any input!

6 Comments
2024/11/09
21:55 UTC

2

Why Does My Loop Only Append Once?

I'm going through freeCodeCamp.org, and I've gotten to the Roman Numeral Converter challenge. I wanted a slightly different answer to the way they did their recursive functions. Here's my version of the Roman Numeral Converter. It does the math properly, but for some reason whenever it needs a duplicate, it only lists the character once. For example, "365" returns CLXV instead of CCCLXV.

It's properly dividing by 100 three times, but the "C" is only added the first time. Why is that?

SOLVED. I was using the modulus operator instead of simply subtracting. Thanks everybody!

10 Comments
2024/11/09
21:45 UTC

0

Something weird with execution order

Hello!

My brain is starting to hurt a little here.

import { HashMap, ArrClass } from "./hashMap"; 
//no asyng stuff inside, just a class with regular functions

// The issue
const map = new HashMap(); 
console.log(map); // Not empty ??? map already contains "johny" in one of the buckets
map.set("johny", "student");
console.log(map); // Filled

// Just to check if I'm crazy
const arr = [];
console.log(arr); // Empty
arr.push("hello")
console.log(arr) // Filled

const obj = {};
console.log(obj) // Empty
obj.value = "test"
console.log(obj) // Filled

// Thinking maybe module is the problem, so I've added ArrClass inside "./hashMap"
const arr2 = new ArrClass; 
console.log(arr2); // Empty
arr2.push("hello")
console.log(arr2) // Filled

I console.log(map) twice, before and after filling it, but for some reason both times it shows up filled.

Regular objects and arrays are working as expected.
Then to test I made new class ArrClass inside a module (just returns [ ]) , but it's working fine as well.

So what's the issue here?

9 Comments
2024/11/09
21:09 UTC

2

WebSocket video streaming automatically adjusts quality based on the user's network status

I have three sources for my WebSocket video streaming, and I'm using JMuxer to display the video in the client's web browser. I need to implement automatic quality adjustment based on network status. For example, if the current stream is at 1080p but the client's network slows down, it should automatically switch to the 720p source.

The available streaming endpoints are:

  • /video?quality=360p
  • /video?quality=720p
  • /video?quality=1080p

I'm aware of the Network Information API, but I want a solution that directly adapts the video quality based on the client's ability to handle the current data stream.

3 Comments
2024/11/09
19:46 UTC

5

How can I detect when a browser or tab is closing (but NOT refreshing) in JavaScript?

I believe there isn’t a native way to do this, though I’ve seen some workarounds, but I’m not sure if they would work.

19 Comments
2024/11/09
17:23 UTC

0

Need guidance on creating a page which will be completely editable by app admin

I need guidance and steps on how can i go about creating a page on a web app which will be completely editable by admin just like elemantor , how do i go on creating a page like this and this has to be done in a wordpress website, how much do you guys think it will take for a intern developer with 7 month experience. This functionality is asked by my company client and my response was that why dont they just use elemantor themselves to edit the page as it will be too complex to make, but my manager said they dont want to use wordpress for anything and we need . Am i correct in thinking that it will be too complex, i made the page to be editable completely for text but i am having hard time with editing image as text is being stored in database so i ask if we can use a service like imagekit where we store image and in code use like so i can store it in db too but it was denied. Please guide me if there is a better solution for it and how can i proceed further thanks

10 Comments
2024/11/09
15:09 UTC

1

How Does YouTube Download Work in Web Browsers?

Hi everyone,

I’m curious about how YouTube’s offline video functionality works in web browsers. Here’s what I’ve observed and would love to get some technical insights from the community.

Recently, I downloaded a video from YouTube using the web version. The video is quite long—about 3 hours—and I was able to watch it offline without any issues once it was downloaded. What puzzles me is that despite the video’s large size, the browser’s cache and storage didn’t show a significant increase in size.

Web browsers typically have storage limits for offline data such as cookies, cache, and local storage, often ranging around 5 MB for these purposes. Given this limit, I’m wondering how YouTube manages to allow such large video downloads and playback in a browser. I’ve tested this across different browsers, and it works perfectly.

Some technical points I’m interested in:

  1. How does YouTube circumvent browser storage limits to enable large video downloads? Is it using some form of server-side storage or special techniques?
  2. What mechanisms are in place to manage and retrieve these offline videos without significantly affecting local storage?
  3. Are there any JavaScript or web API methods YouTube employs to handle this efficiently?

I would really appreciate any technical explanations or insights into how this works.

Disclaimer: I don’t have YouTube Premium. I’ve noticed that in my current country (where YouTube is automatically set to a local version), I’m able to download videos and watch them offline without ads. This could be due to the fact that there are fewer advertisers here, and many people don’t speak English or use Latin script.

Thanks in advance for your help!

11 Comments
2024/11/09
14:32 UTC

4

How to solve and learn leetcode challenges as a self-taught developer?

hey , i'm a self-taught web developer , i was trying to solve leetcode challenges but i couldn't finish that , first of all the math is very hard for me , i don't even understand what is it , it was some BIT calculation. every time i try to solve i end up with others solution or chatGPT Assist. how can i improve where should i start?

11 Comments
2024/11/09
13:06 UTC

1

Beginner looking for tutorials on using ChatGPT API with Node.js

I want to learn how to work with the ChatGPT API using Node.js and create a web-based tool to handle concurrent requests. While I have some basic knowledge of HTML, CSS, and JavaScript, I'm completely new to Node.js, API integration, and server-side development.

Could anyone recommend some beginner-friendly tutorials or examples that specifically focus on:

  • Setting up Node.js with ChatGPT API
  • Building a web application with concurrent processing
  • Integration with ChatGPT and image AI endpoints
  • Server setup and deployment basics

Looking for something practical and straightforward that can get me started quickly. Thanks in advance!

0 Comments
2024/11/09
07:50 UTC

0

How to build logics in js

Hey guys I am learning JavaScript from the Angela udmey course but when she explained like for example Arrays etc I get everything like how arry works idex valus etc but when she give a problem to solve ... I try much something I also solve the problem but sometimes I can't even think like that I try so hard to do but until I see the solution I can't solved it .

That's make my confidence very down

Any suggestions guys how you tackle this situation when we guys start learning JavaScript

Thankyou so much

28 Comments
2024/11/09
04:44 UTC

1

Trouble Integrating FullCalendar and RRule Plugin

Hello friends,

I'm trying to use FullCalendar with Vanilla JavaScript, but I’m stuck with issues when adding the rrule plugin. Here’s what I’ve tried:

  1. Using CDN (Partial Success)

Using the CDN, FullCalendar works well without the rrule plugin, but when I add it, I get the error:

"e is not iterable"

CDN Setup:

<script src="https://cdn.jsdelivr.net/npm/@fullcalendar/core@latest/main.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@fullcalendar/daygrid@latest/main.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@fullcalendar/timegrid@latest/main.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@fullcalendar/rrule@latest/main.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/rrule@latest/dist/es6/rrule.min.js"></script>
<script type=“text/javascript" src="_fullcalendar.js"></script>

// _fullcalendar.js

document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
        plugins: [ dayGridPlugin, timeGridPlugin, rrulePlugin ],
        initialView: 'dayGridMonth',
        events: [
            {
                title: 'Recurring Event',
                rrule: { freq: 'weekly', interval: 1, byweekday: [ 'mo', 'we', 'fr' ] }
            }
        ]
    });
    calendar.render();
});

2. Using NPM (Module Resolution Issues)

Switching to an NPM setup to try to resolve this, I ran into import issues right away.

Installed packages:

npm install u/fullcalendar/core u/fullcalendar/daygrid u/fullcalendar/timegrid u/fullcalendar/rrule rrule

// _fullcalendar.js:
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import rrulePlugin from '@fullcalendar/rrule';

const calendarEl = document.getElementById('calendar');
const calendar = new Calendar(calendarEl, {
    plugins: [ dayGridPlugin, timeGridPlugin, rrulePlugin ],
    initialView: 'dayGridMonth',
    events: [{ title: 'Recurring Event', rrule: { freq: 'weekly', interval: 1, byweekday: [ 'mo', 'we', 'fr' ] } }]
});
calendar.render();

Error:

"Uncaught TypeError: Failed to resolve module specifier '@fullcalendar/core'. Relative references must start with either '/', './', or '../'"

in conclusion…

CDN: Works except for rrule (error: "e is not iterable").

NPM: Module resolution errors with relative paths.

Any guidance on resolving these import and plugin issues would be much appreciated!

4 Comments
2024/11/09
01:30 UTC

0

What do you call the directories in javascript?

i dont know what the name of this is, but an example is:
this._spriteset._tilemap.lowerZLayer

3 Comments
2024/11/09
01:26 UTC

0

Healthbar for my characters won't work!

I’ve got a work assignment from my professors to continue to build on his html and css file with a JavaScript of my own and I am not allowed to changed the HTML or CSS.

The whole assignment is three interactive character’s is fighting a dragon. The principial is that when a character’s attack is, the dragon is going to retaliate with is own attack. Aswell as when a character gets attacked their hp is supposed to go down. Each characters have their own hp bar.

I have gotten most stuff to work, no problem but I’ve seemed to get the health bar to go down for my heroes. The dragon was no problem at all, it just seems to not want to work. I’ve tried every ai and googling to find out why it wont work, but nothing seems to work.

Btw some of the comments is made in norwegian!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Arbeidskrav PGR102</title>
    <link rel="stylesheet" href="arbeidskrav.css" />
  </head>
  <!-- HTML KODEN TRENGER DU IKKE RØRE FOR Å LØSE OPPGAVENE. DU SKAL KUN KODE I SCRIPT -->

  <body>
    <div class="main-container">
      <div class="hero-health-containers">
        <div class="healthbar-container">
          <!-- healer-health sin vidde må forandres for å endre lifebar -->
          <div id="healer-health" class="healthbar"></div>
          <div class="text-container">
            <!-- Disse må forandres på for å endre på navn og HP -->
            <p id="healer-name-txt">Henriette Healer</p>
            <p id="healer-health-txt">400 / 400 HP</p>
          </div>
        </div>
        <div class="healthbar-container">
          <!-- archer-health sin vidde må forandres for å endre lifebar -->
          <div id="archer-health" class="healthbar"></div>
          <div class="text-container">
            <!-- Disse må forandres på for å endre på navn og HP -->
            <p id="archer-name-txt">Ariana archer</p>
            <p id="archer-health-txt">600 / 600 HP</p>
          </div>
        </div>
        <div class="healthbar-container">
          <!-- warrior-health sin vidde må forandres for å endre lifebar -->
          <div id="warrior-health" class="healthbar"></div>
          <div class="text-container">
            <!-- Disse må forandres på for å endre på navn og HP -->
            <p id="warrior-name-txt">Wyona Warrior</p>
            <p id="warrior-health-txt">800 / 800 HP</p>
          </div>
        </div>
      </div>

      <!-- Healthbar til fienden -->
      <div class="dragon-health-container">
        <div class="healthbar-container">
          <!-- dragon-health sin vidde må forandres for å endre lifebar -->
          <div id="dragon-health" class="healthbar"></div>
          <div class="text-container">
            <!-- Disse må forandres på for å endre på navn og HP -->
            <p id="dragon-name-txt">Daar Dragon</p>
            <div id="dragon-health-txt" class="text-container">
              2000 / 2000 HP
            </div>
          </div>
        </div>
      </div>

      <!-- Bildecontainere for heroene. Disse bilde-containerne skal kunne trykkes på  -->
      <div id="healer" class="img-container">
        <img class="hero" src="assets/healer.png" />
      </div>
      <div id="archer" class="img-container">
        <img class="hero" src="assets/archer.png" />
      </div>
      <div id="warrior" class="img-container">
        <img class="hero" src="assets\warrior.png" />
      </div>

      <!-- Bildecontainer for fienden -->
      <div id="dragon" class="img-container">
        <img id="dragon-img" src="assets\dragon.png" />
      </div>
    </div>
    <script>
      //Denne JS-koden er laget klar for deg. Den trenger du ikke endre på. :-)
      //Stats for heroes: Du må ikke bruke alle stats videre i programmet ditt hvis du ikke ser det nødvendig.
      //Husk at for å hente ut noe fra et objekt som er i et array kan vi skrive for eksempel slik: heroesArray[1].name (Ariana Archer)

      let heroesArray = [
        {
          id: 0,
          name: "Henriette Healer",
          maxHP: 400,
          currentHP: 400,
          damage: 100,
          alive: true,
        },
        {
          id: 1,
          name: "Ariana archer",
          maxHP: 600,
          currentHP: 600,
          damage: 400,
          alive: true,
        },
        {   
          id: 2,
          name: "Wyona Warrior",
          maxHP: 800,
          currentHP: 800,
          damage: 400,
          alive: true,
        },
      ];

      let dragonStats = {
        name: "Daar Dragon",
        maxHP: 2000,
        currentHP: 2000,
        damage: 200,
        alive: true,
      };

      //Bildene som skal kunne trykkes på
      const healer = document.getElementById("healer");
      const archer = document.getElementById("archer");
      const warrior = document.getElementById("warrior");

      const dragon = document.getElementById("dragon");

      //Navnene til heltene og dragen som kan oppdateres med riktig navn (tilleggsfunksjonalitet)
      const healerName = document.getElementById("healer-name-txt");
      const archerName = document.getElementById("archer-name-txt");
      const warriorName = document.getElementById("warrior-name-txt");

      const dragonName = document.getElementById("dragon-name-txt");

      //HP-tekstene til heltene som skal kunne oppdatere seg (tilleggsfunksjonalitet)
      const healerHealthTxt = document.getElementById("healer-health-txt");
      const archerHealthTxt = document.getElementById("archer-health-txt");
      const warriorHealthTxt = document.getElementById("warrior-health-txt");

      //HP-teksten til dragen som kan oppdatere seg (tilleggsfunksjonalitet)
      const dragonHealthTxt = document.getElementById("dragon-health-txt");

      //Healthbars som må oppdateres for at grønnfargen skal bli mindre når HP blir mindre (tilleggsfunksjonalitet)
      const healerHealthBar = document.getElementById("healer-health");
      const archerHealthBar = document.getElementById("archer-health");
      const warriorHealthBar = document.getElementById("warrior-health");

      const dragonHealthBar = document.getElementById("dragon-health");

      //Her kommer din kode! :o

      //  Først lager jeg felles angreps-funksjon for både heltene og dragen med denne felles betegenselen vil det komme en alert på både at heltene og dragen angrep
      
      //  Først med denne funksjon ønsker jeg at for hver gang en av heltene angriper trekker dette fra hp til dragen, noen så vil variere basert på heltens angrep 
      
       // Function to update the health bar
  function updateHealthBar(character, healthTxt, healthBar) {
    healthTxt.textContent = `${character.currentHP} / ${character.maxHP} HP`;
    const healthPercentage = (character.currentHP / character.maxHP) * 100;
    healthBar.style.width = `${healthPercentage}%`;
  }

  // Attack function for the characters
  function attack(hero, dragon) {
    // Check if the hero is alive
    if (!hero.alive) {
      alert(`${hero.name} kan ikke angripe siden dem er dø!`);
      return; // Early exit if hero is dead
    }

    // Hero attacks the dragon
    alert(`${hero.name} har gjort ${hero.damage} skade på ${dragon.name}!`);
    dragon.currentHP -= hero.damage;
    dragon.currentHP = Math.max(dragon.currentHP, 0); // Prevent negative health

    // Update dragon's health display
    updateHealthBar(dragon, dragonHealthTxt, dragonHealthBar);

    // Ser om dragen er 
    if (dragon.currentHP <= 0) {
      dragon.alive = false;
      alert(`Gratulerer, du har vunnet!`);
      return; // Exit since dragon is defeated
    }

    // Dragon retaliates
    let randomIndex = Math.floor(Math.random() * heroesArray.length);
    let randomHero = heroesArray[randomIndex];

    if (randomHero.alive) {
      alert(`${dragon.name} har angrepet ${randomHero.name}!`);
      randomHero.currentHP -= dragonStats.damage; // Fixed reference to dragonStats.damage
      randomHero.currentHP = Math.max(randomHero.currentHP, 0);

      // Check if hero is defeated
      if (randomHero.currentHP === 0) {
        randomHero.alive = false;
        alert(`${randomHero.name} er død!`);
      }

      // Update hero's health display
      updateHealthBar(
        randomHero, 
        document.getElementById(`${randomHero.name.toLowerCase().split(' ')[0]}-health-txt`), 
        document.getElementById(`${randomHero.name.toLowerCase().split(' ')[0]}-health`)
      );
    }
  }

  // Event listeners for hero clicks
  healer.onclick = function() {
    attack(heroesArray[0], dragonStats);
  };
  
  archer.onclick = function() {
    attack(heroesArray[1], dragonStats);
  };

  warrior.onclick = function() {
    attack(heroesArray[2], dragonStats);
  };

    
    </script>
  </body>
</html>

 

 

3 Comments
2024/11/09
00:05 UTC

5

Can someone please tell me what the hell this code does?

const { genericPool: pool } = getPool(dbname);

It's declaring a constant, as a dictionary!? Or something? What is genericPool? When I look in the debugger it seems like only pool exists... I'm lost.

edit yall are awesome thanks

18 Comments
2024/11/08
23:01 UTC

0

How do I detect if script is loading, loaded or failed?

Hey. So, I have two scripts on a page, added separately from each other, let's call them A and B. I need script B to do it's thing, but only and exclusively if script A already loaded.

Here are the properties of Script A:

  • It may be present on a page. It is added in projects that I have no control over. Same with script B
  • It doesn't modify global scope
  • It may be loaded before or after script B
  • It may be not included in page at all
  • It may fail to load (network problems, browser problems, server problems)

What I did so far. First, I'm checking if sccript A is already present. If not, I add MutationObserver to monitor if it will be added later. If it is added later, I attach two events - load and error. I requested for script A to have some presence in global scope that I can see (it will probably be rolled out next year, definitely not earlier).

Now, the problem that I am facing is knowing if script already loaded or already failed. For example, I did querySelector and found script. I can attach event listeners to it, but if those events already happened, they will not trigger. I can attach timeout, but timeout will trigger even if all is good (or if all is bad), sometimes before actual load/error happens. Is there any way to know state of particular script on a page, like we can with DOM (via loadingstate)?

9 Comments
2024/11/08
21:24 UTC

1

network graph library with customizable nodes and connections

Hi all, I would like to create an interactive graph/visualization with js. Something like this:

https://imgur.com/a/YuSwcmT

I searched for some graph libraries but it seems they have limited customization. Or maybe I am missing something because I didn't make any graphs with js yet.

Could you recommend me some library to try?

Thank you.

1 Comment
2024/11/08
20:37 UTC

1

How to open accordion from in-page anchor tag

I took over a project and can't figure out how the accordion currently functions (i.e. using js or pure css). I can't find it.

Below is the code to display the list of services, when you click on the service, the content opens up.

<div class="service-item">
                        <input class="service-checkbox" type="checkbox" name="collapse<?php echo $the_increment; ?>" id="<?php echo $exp_post->post_name; ?>"  />
                        <label class="service-label" for="<?php echo $exp_post->post_name; ?>">                            <span class="service-title">
                                <?php echo $exp_post->post_title; ?>
                            </span>
                        </label>
                        <div class="service-content">
                            <div class="post-excerpt"><?php echo $exp_post->post_excerpt; ?></div>
                        </div>
                    </div>

I have an image carousel of popular services, when clicked, it scrolls down to the correct service based on ID but now I need to have the content opened.

Can someone help me with this? I'm at a lost on how to do this as JS/JQuery is not my forte.

2 Comments
2024/11/08
19:33 UTC

2

Detecting Window Object Changes via Proxy to pass through to Chrome Extension

I'm creating a Chrome extension that grabs information from a browser game to update an overlay that displays team information. To do this, I have injected JS into the browser page to pass data from the browser to the extension through window.postMessage().

Here is the full code for the injected JS

// setInterval(function () {
//     window.postMessage({ data: window.gameInfo.party}, "*")
// }, 1000);
// This worked but felt like an unoptimized solution

let partyData = window.gameInfo.party[0];

let handler = {
    set(target, property, value, receiver) {
      if (value !== target[property]) {
        console.log(`Setting ${property} to ${value}`);
        target[property] = value;
        console.log(property, value);
        return true;
      }
      return false;
    }
  };
  
let proxyParty = new Proxy(partyData, handler);

Right now, if I call partyProxy or partyData , it comes up as undefined. window.gameInfo.party[0] works as intended when entering it into the browser console.

My ultimate goal is to have the function that includes window.postMessage() be triggered when there is a change to window.gameInfo.party[0]. If it matters, window.gameInfo.party[0] is an array that includes "name" and "level" values.

My JS knowledge is limited and I'm much more of a visual learner, so I haven't found a video that addresses this exactly. I'm having trouble parsing the documentation to get a clear answer on how to accomplish this.

Thank you so much for any help!

4 Comments
2024/11/08
18:44 UTC

1

Passing large amount of calculated between routes (ExpressJS)

I am using ExpressJS to build an app that will compare two employee datasets - one is in a csv, one is in a database.

I have written some middleware logic that will:

  • compare employee ID to show me new employees in the csv that don't exist in the database
  • compare employee ID to show me if employee details are different on the csv (LName, address, etc.) than what is in the databse

I then send this information to a view that the user can compare before they commit the changes.

My question lies here: Since all of the calculations have been performed, is there a way for me to send this data to a post route to commit the changes? A few considerations:

  • I can't use app.local since there can be potentially multiple users accessing the app at the same time.
  • I can't use cookies/session to store the data since it contains personally identifiable information and I don't want to store that on the user's computers.

So far, my approach is that that if the user accepts the changes, I will just rerun the calculations on the post route, but I figure there has to be a better way.

5 Comments
2024/11/08
18:16 UTC

1

How to run a JS SDK API payment gateway on WordPress?

The payment gateway provider has a wordpress plugin but it does not have all the gateway functions built in and also they have a seperate portal made available to merchants to get following data;

Merchant ID : API Key : Merchant Secret Key : Confirmation Endpoint Endpoint

Private key

Download Server Public key

Download Public key

Download

Their most uptodate plugin can be downloaded here; npmjs. com/package/directpay-ipg-js

IPG User Wise Card Management API Documentation justpaste. it/7w34p

IPG Integration Payment Link V1.0.1 Integration document justpaste .it/gj7ny

To access above links pls copy it and remove the space between the dot

I need support to help setup all this on wordpress explain steps need to setup as If I know nothing about JS, HTML, CSS or APIs

Installed plugin provided by them and researched all options inside their merchant portal but those functions provided by sdk seem to have no GUI to be easily accessed and edited

0 Comments
2024/11/08
17:54 UTC

0

Can I use the Instagram API to get recent posts with a specific hashtag without giving my phone number to META?

Hi everyone!

I'm trying to make an app that finds recent posts with a specific hashtag. The Instagram API documentation sent me to META and it seems like I need to verify my account with a phone number - something I really don't want to do.

Any ideas if there is another way to get what I want?

Thanks!

3 Comments
2024/11/08
16:22 UTC

0

Tailwind custom addded utility Classes Not applying when html is rendered in JavaScript file using innerHTML

So the issue is that the utility classes are working perfectly fine with My index.html file when are called there on normal html with tailwindcss, but when i try to render that html in my javascript using innerHTML, the classes dont work no more. The styles here tailwind the config file, work perfectly fine with the rendered innerHTML elements in the javascript , unlike the ones added in the input.css file why could be the issue? why is that happening i've been searching for a long time but didn't find anything.

HERE ARE LINKS TO MY CODE PICTURES :

Input.css Utility classes FILE : https://preview.redd.it/tailwind-custom-addded-utility-classes-not-applying-when-v0-si5mmoiw6ozd1.png?width=2560&format=png&auto=webp&s=aa7baf1d3c76a332ecbd52367e5fe36482e6a590

tailwind.config.js FILE : https://preview.redd.it/tailwind-custom-addded-utility-classes-not-applying-when-v0-5sp7m6r7iozd1.png?width=2560&format=png&auto=webp&s=cf0a471cd22476bca08e78d9030bdf4eb59fde3a

Index.html FILE : https://preview.redd.it/tailwind-custom-addded-utility-classes-not-applying-when-v0-inplm90y6ozd1.png?width=2560&format=png&auto=webp&s=8ecd21ed76f2ecff4d654b60be4d9a07721510b0

JavaScript innerHtml element render: https://preview.redd.it/tailwind-custom-addded-utility-classes-not-applying-when-v0-34suhre07ozd1.png?width=2560&format=png&auto=webp&s=21d3aaa8b0d7393e59c67ad73a2cf71cc530a44f

AND THIS IS THE FUNCTION IN CHARGE OF THE ANIMATION ( WORKING PERFECTLY ) : https://preview.redd.it/tailwind-custom-addded-utility-classes-not-applying-when-v0-s0ey0sc47ozd1.png?width=2560&format=png&auto=webp&s=050831f6efdef4c5877b71015b856f161217211d

PACKAGE.JSON FILE : https://preview.redd.it/tailwind-custom-addded-utility-classes-not-applying-when-v0-orzqeow8wozd1.png?width=2560&format=png&auto=webp&s=2d062da8133a14d11999ca71ea6974b5de8f6d70

5 Comments
2024/11/08
16:22 UTC

1

custom javasript help for Google Tag Manager

Hi javascript pros!

Could anyone help to modify this code to work with these types of datalayers?

Here's the code, it extracts the value of the item_id:

function() {
    // Find the correct ecommerce object in the dataLayer
    var ecommerceObject = null;
    for (var i = 0; i < window.dataLayer.length; i++) {
        if (window.dataLayer[i].ecommerce) {
            ecommerceObject = window.dataLayer[i].ecommerce;
            break;
        }
    }

    // Check if the ecommerce object and items array exist
    if (ecommerceObject && ecommerceObject.items) {
        var itemIds = ecommerceObject.items.map(function(item) {
            return item.item_id;
        });
        return itemIds;
    } else {
        // Return an empty array if ecommerce items are not found
        return [];
    }
}

Here is the datalayer:

dataLayer.push({

event: "view_item",

eventModel: {

currency: "USD",

value: 90,

items: [

{

item_id: "4524138",

item_name: "Blue car toy",

item_brand: "BoxToys",

price: 90,

quantity: 1

}

]

},

gtm.uniqueEventId: 268

})

Thank you!

1 Comment
2024/11/08
11:41 UTC

Back To Top