r/programminghelp • • 18d ago

JavaScript BEGINNER CODER: Stuck with a migrations error

0 Upvotes

Hi,

I'm working on an adonisjs project and I'm having issues with migrations. I don't think I'm using the wrong command. I'm doing:

node ace make:migration (migration name here)

Then:

node ace migration:run

My project is on github. Apologies the migrations folder is a little cluttered. The ones with issues are the "item" and "item_comments" ones:

https://github.com/Ajaz754/adonisjs-project-22-.git

The error is:

C:\Windows\System32\adonis22>node ace migration:run
❯ error database/migrations/1794008714673_alter_item_comments_table
[ error ] INSERT INTO "_knex_temp_alter555" SELECT * FROM "item_comments"; - no such table: main.item

Please correct me if I'm wrong but I thinks its saying my "item" table doesnt exist which doesnt make sense since its clearly my 'schema.ts'. It said the same error before for the "user" table aswell.

Any help would be much appreciated

TIA

r/programminghelp • • Oct 25 '26

JavaScript Beginner Coder: Stuck with an error

2 Upvotes

Hi,

I'm working on an adonisjs project. l've ran into an error

My project is on github:

https://github.com/Ajaz754/adonisjs-project-22-.git

The error is in file 'database/seeders/ product_seeder.ts' Line 10

The error is:

Object literal may only specify known properties, and 'userld' does not exist in type
'OneOrMany<Partial<ModelAttributes<Product>>>.

Any help would be much appreciated

TIA

r/programminghelp • • Sep 07 '25

JavaScript Constant error message when opening any .js file

1 Upvotes

Any time I open a .js file it brings me up with the same error code 800A03EA. I know little to nothing about coding, only a bit of python but no Javascript, so if someone could help me I would like to know how I can fix this, thanks.

r/programminghelp • • Jan 03 '26

JavaScript Any good way in JavaScript to store a rendered image on the client side?

4 Upvotes

I have a Mandelbrot set rendering tool that runs on my website (http://weirdly.net/webtoys/mandelbrot/). It works ok, but one thing that I'm looking to optimise is the rendering of thumbnail images.

It has an option to save any rendering you create, which stores all of the info that's used to render the image in localStorage and creates a thumbnail that you can later click on to load it back up.

The problem I'm running into is the loading time for those thumbnails. When the page loads it runs through rendering them. Each one takes a fraction of a second, but once you have enough, you end up waiting a significant amount of time for them to finish.

I can think of a couple of solutions, but neither is great. I could base64 encode the thumbnails and throw them into localStorage, but that would be far too much data for the available space. I could have it upload thumbnails to the server, ready to grab on page load, but that's more potential bandwidth and storage than I want to spend.

Is there any way to cache those images in the browser? That would be ideal.

Any other ideas?

If you want to look at the code, it can be found on my GitHub account at https://github.com/jacobEwing/webtoys/tree/main/mandelbrot, or as previously mentioned, on my site.

r/programminghelp • • Oct 13 '24

JavaScript Need help with JS

1 Upvotes

on the website you choose from 4 themes when you choose one new page opens an that theme's picture is displayed with 10 different sentences 5 correct 5 incorrect, 5 correct ones have their predetermined place it goes in(like a list) so if they choose predetermined 2nd and then 1st it doesn't mix up and when they get chosen they get displayed on the right side of the screen, i cant seem to do this, and this selection process needs to happen 3 times in total, it only does it twice and in the end all sentences needs to be displayed on a new page. relevant code- https://paste.gg/p/anonymous/cab0dcea63c5431abdc9388b35253490 this is just one page of 4themes all are the same expect for sentences. So i need help with assigning predetermined numbers to correct sentences and i cant seem to figure out how to do this selection process 3 times instead of 2.

I can send you full code of the website if needed.

r/programminghelp • • Jun 08 '26

JavaScript need help for a class project!

2 Upvotes

hello! this is my first coding class and i have a final project due soon thats nearly done. i'm having trouble with one thing and i'm too shy to ask my prof.

i dont know how to make my js function result show here

i'm unsure of what to put here to have the fetch api response show here. the function works but i just don't know to make it so when i click the "get-answ-b.png" it shows the response on the next page.

any help?

r/programminghelp • • Nov 12 '22

JavaScript How to run a JS program?

1 Upvotes

Hey so I've been trying to run a js file in local host but it refuses to connect. I also tried nodejs and it doesn't recognize my file. What else could I do.?

r/programminghelp • • Jan 15 '26

JavaScript create a unique chat instance for a unique javascript game instance

2 Upvotes

I am developing a game that requires chat feature, Everyone who starts the game is asked to enter a password for the game, once he does, he gets a shareable link which he can share to the team. Once people have this shareable link, they can join the unique game instance. Each game instance can have 100-200 users and multiple game instances can be spawned.

I need to create a chat for each unique instance of the game created, the chat can be temporary with no persistent history maintained but members of the same game session are able to access it and just as long as the game session is active the chat should persist.

Anyone who joins the unique game instance should be able to access the chat. What's the best, quickest and cheapest way to implement this feature.

I'm open to third party library or services, or using any existing services available, but, it has to have the feature to have this unique session that only the unique game instance members can access.

r/programminghelp • • Dec 30 '24

JavaScript Function in JS returns completely fine results, but checking the value sometimes doesnt work?

1 Upvotes

Here is my function that calculates the hand:

function calculateHandValue(hand) {
        let value = 0;
        let hasAce = false;

        for (let card of hand) {
            if (card.value === 'A') {
                hasAce = true;
            }
            value += getCardValue(card);
        }

        if (hasAce && value + 10 <= 21) {
            value += 10;
        }
        return value;
    }

and it works completely flawlessly. And then I go and check its value in another function, and even though the value is fine, it returns much bigger number? There are no indicators about what's wrong, I tried writing it out, logging it, constantly fine results.

function playerHit() {
        playerHand.push(dealCard());
        var val = calculateHandValue(playerHand);
        updateUI();
        if (val > 21) {
            endGame('You busted! Dealer wins');
        }
    }

and just for the record, updateUI() doesn't do anything except updating the labels which isnt connected to this problem.
Anybody have any idea? My brain is starting to fall apart from JS code that works but doesnt?

Edit: I found out that when you really bust one time, you will always bust unless it's a special case(u have an ace)

r/programminghelp • • Mar 23 '26

JavaScript Programming issues with a Dc bot - API and RSS

Thumbnail reddit.com
1 Upvotes

r/programminghelp • • Jul 15 '25

JavaScript Trouble making recursive functions

2 Upvotes

I understand that with recursion you have a base case, something that ends the function. And then you have a reason to have the function call itself. But I'm having trouble looking at a for loop and mentally converting it to a recursive function. With for loops am I basically replacing the initializer of the for loop with a call to the recursive function and passing along that initializer as the argument?

r/programminghelp • • May 01 '24

JavaScript Javascript returning undefined from Array, with no errors in console.

0 Upvotes

I have this code within a function, giving me a random cell from an array:
nameBox.value = randName[Math.round(Math.floor(Math.random()*randName.length))];

This works exactly as intended. However, I realized that I will probably be using this again, so I want to make it into a separate function, using arguments, like so:
function getRand(e){e[Math.round(Math.floor(Math.random()*e.length))];};
and then just run getRand(randName); in the previous function.

The newly created function is a copy/paste of the first line I provided, with "randName" replaced by "e." However, when I try to run it, it returns undefined, with no error in console. Any ideas why?

r/programminghelp • • May 25 '24

JavaScript Testdome in JavaScript for a job

2 Upvotes

Hi!

I've been sent a test for a job as a webbdeveloper. It's been a while since i coded javascript and i was wondering if anyone knows what kind of javascript questions i should probably study on?

All i Know is there are 3 questions and 2 of them are supposed to be "easy" and one difficult and i have 1,5h to complete the test. I have to score minimum 35% correct to move on in for the job.

any suggestions on where I should start with practicing?

r/programminghelp • • Oct 07 '26

JavaScript Need Guidance

Thumbnail reddit.com
1 Upvotes

r/programminghelp • • Dec 13 '23

JavaScript I'm trying to move HTML Form data to a MySQL Database using JS. Whenever I try to use the mysql/mysql2 package, it sends an error. I've tried fixing it with a different syntax, but it still doesn't work. Is this a web browser issue, a computer (Mac) issue, or something else?

2 Upvotes

The needed JS code:

function createAccount() {
let { createConnection } = require("mysql2");
let con = createConnection({
"host": "localhost",
"user": "root",
"password": "password",
"database": "mydb",
})
con.connect((err) => {
if (err) throw err; else console.log("Connected");
})
let newUsername = document.getElementById("createUsername").value;
let newEmail = document.getElementById("addEmail").value;
let newPass = document.getElementById("createPass").value;
let sql = \INSERT INTO userInfo (username, email, pass) VALUES (${newUsername}, ${newEmail}, ${newPass})`;con.query(sql, (err, result) => {if (err) throw err;console.log(`${result.affectedRows} Record(s) Updated`);})}`

The error:

Uncaught ReferenceError: require is not defined
at createAccount (login.js:72:32)
at HTMLInputElement.onclick (VM824 login.html:1:1)

If let { createConnection } = require("mysql2") is changed to import { createConnection } from "mysql2":

Uncaught SyntaxError: Cannot use import statement outside a module (at login.js:1:1)

Changing "mysql2" to "Mysql" doesn't change the error

r/programminghelp • • Aug 07 '22

JavaScript Need help transforming this javascript into HTML

2 Upvotes

hey, started learning javascript 4 days ago, and had learned HTML like 5 years ago, and I'm trying to put my code into HTML but, even after searching for a while, wasn't capable of doing so. Can anyone help me? (oh and also if there's some way to make this shorter would help me a lot)

Here's the code:

var a = {
  price: 1,
  rating: 2,
  distance: 3
};
var b = {
  price: 2,
  rating: 3,
  distance: 3
};
var c = {
  price: 3,
  rating: 2,
  distance: 1
};
function hotelInfo(d) {
  console.log("hotel info");
  console.log("price: " + d.price);
  console.log("rating: " + d.rating);
  console.log("distance: " + d.distance);
}
console.log(hotelInfo(a));
console.log(hotelInfo(b));
console.log(hotelInfo(c));
function hotelcheck(x, y, z) {
  if (x.price < y.price && x.price < z.price) {
    console.log("x has the smallest price");
  }
  if (y.price < x.price && y.price < z.price) {
    console.log("y has the smallest price");
  }
  if (z.price < x.price && z.price < y.price) {
    console.log("z has the smallest price");
  }
  if (x.rating > y.rating && x.rating > z.rating) {
    console.log("x has the top rating");
  }
  if (y.rating > x.rating && y.rating > z.rating) {
    console.log("y has the top rating");
  }
  if (z.rating > x.rating && z.rating > y.rating) {
    console.log("z has the to rating");
  }
  if (x.distance < y.distance && x.distance < z.distance) {
    console.log("x makes you walk less");
  }
  if (y.distance < x.distance && y.distance < z.distance) {
    console.log("y makes you walk less");
  }
  if (z.distance < x.distance && z.distance < y.distance) {
    console.log("z makes you walk less");
  }
}
console.log(hotelcheck(a, b, c));

r/programminghelp • • Dec 14 '23

JavaScript Issue with play() in js

1 Upvotes

Im trying to make a basic alarm clock website but the noise of the alarm only plays after the pop up is dismissed, but after that it plays automatically when the alarm rings. When I check console it said that play() can only be initiated by a user interaction and I was hoping if someone could give me a work around for this error

js code:

    let alarmTime = '';
let x = 1
var audio = new Audio('alarm.wav');


function updateClock() {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  document.getElementById('clock').innerHTML = `<span class="hour">${hours}</span>:<span class="minute">${minutes}</span>:<span class="second">${seconds}</span>`;
}

function checkAlarm() {
  const now = new Date();
  const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;

  if (alarmTime === currentTime && x==1 ) {
    document.getElementById('alarmMessage').textContent = 'Wake up!';
    document.getElementById('alarmMessage').style.display = 'block';
    audio.play();
  } else if(alarmTime != currentTime) {
    x = 1
  }
}

function setAlarm() {
  alarmTime = document.getElementById('alarmInput').value;
  document.getElementById('alarmInputPopup').style.display = 'none';
  document.getElementById('alarmMessage').style.display = 'none';
  if (alarmTime != ''){
    document.getElementById('currentAlarmTime').textContent = `Alarm set for: ${alarmTime}`;
  } else {
    document.getElementById('currentAlarmTime').textContent = ''
  }
  setInterval(checkAlarm, 1000);
}


document.getElementById('setAlarmBtn').addEventListener('click', () => {
  document.getElementById('alarmInputPopup').style.display = 'block';
});

document.getElementById('setAlarmPopupBtn').addEventListener('click', () => {
  setAlarm();
});

document.getElementById('alarmMessage').addEventListener('click', () => {

    document.getElementById('alarmMessage').textContent = '';
    document.getElementById('alarmMessage').style.display = '';
    x = 0
    
});

setInterval(updateClock, 1000);
updateClock(); // Initial call to display the clock immediately

r/programminghelp • • May 25 '22

JavaScript How to deal with SendPulse access token expiration time? [Node.js]

1 Upvotes

Hi, I'm writing a program to develop a telegram chatbot in Node.js using SendPulse telegram API. The issue I'm facing is that the access_token has a expiration time of 1hour. It generates new access token every hour so I have to change the Authorization value every hour or it gives unauthorized action error. How do I deal with this??

Reference: https://sendpulse.com/integrations/api

r/programminghelp • • Mar 06 '25

JavaScript I have problems working with async/await and local json file. I have been debugging and smashing my head on table for the past 24 hours!

1 Upvotes

My folder structure:

/shopping-cart-dop-shit-2/
│── docs.md
│── index.html
│── items.json
│── script.js
│── shoppingCart.js
│── store.html
│── store.js
│── style.css
│── team.html
│── Assets/
│   │── blue.jpg
│   │── darkGrey.jpg
│   │── green.jpg
│   │── icon-cart-white.svg
│   │── lightGrey.jpg
│   │── orange.jpg
│   │── purple.jpg
│   │── red.jpg
│   │── userAvatar01.svg
│   │── userAvatar02.svg
│   │── userAvatar03.svg
│   │── userAvatar04.svg
│   │── userAvatar05.svg
│   │── userAvatar06.svg
│   │── userAvatar07.svg
│   │── userAvatar08.svg
│   │── userAvatar09.svg
│   │── yellow.jpg
│── docs/
│   │── process.md
│── util/
│   │── formatCurrency.js

Things to considerate:

  1. Both the index.html and store.html links only script.js

  2. opening the store.html and refreshing it 2-3 times gives this console error:

Error: Error fetching data: 
TypeError {}
message: "Failed to fetch"
stack: "TypeError: Failed to fetch↵ at window.fetch (http://localhost:8158/mguxb9xw_console.js:8:221620)↵ at fetchData (http://localhost:8158/shoppingCart.js:13:28)↵ at setupShoppingCart (http://localhost:8158/shoppingCart.js:21:9)↵ at http://localhost:8158/script.js:4:1"
get stack: ƒ ()
set stack: ƒ ()
[[Prototype]]: Object

3. Open store.html and adding items in store.html and when I refresh the page 2-3 times it gives this error: and I cant add any items after that

TypeError: Cannot read properties of undefined (reading 'id')
at http://localhost:8158/shoppingCart.js:55:25
at Array.forEach (<anonymous>)
at renderCartItems (http://localhost:8158/shoppingCart.js:47:16)
at setupShoppingCart (http://localhost:8158/shoppingCart.js:22:3)

4. Clearing the localStorage and trying does not solve any problem

5. I threw both my code and errors at AI tools for help, but instead of fixing the bug, we both ended up more confused—now it feels like the AI is debugging me!

The contents of my code:

index.html

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" type="module"></script>
    <title></title>
  </head>
  <body>
    <header class="header">
      <div class="container header__container">
        <nav class="menu">
          <a class="menu__link menu__link--active" href="index.html">Home</a>
          <a class="menu__link" href="store.html">Store</a>
          <a class="menu__link" href="team.html">Team</a>
        </nav>
        <div class="cart">
          <button class="cart__btn">
            <img src="Assets/icon-cart-white.svg" alt="cart icon" />
            <span class="cart__quantity"></span>
          </button>
          <div class="cart__items-wrapper">
            <div class="cart__items"></div>
            <div class="cart__total-wrapper">
              <span>TOTAL</span>
              <span class="cart__total">$0.00</span>
            </div>
          </div>
        </div>
      </div>
    </header>

    <section class="container ps">
      <h2>Some Of Our Amazing Products</h2>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae assumenda
        totam, animi libero hic voluptas reiciendis nesciunt id ad ipsum
        doloremque nisi qui esse nam est sapiente, explicabo ab beatae
        repellendus, perferendis cupiditate facilis. Beatae quod repellat
        expedita! Numquam, et!
      </p>
    </section>

    <section class="products container">
      <div>
        <img class="products__img" src="Assets/blue.jpg" alt="product image" />
      </div>
      <div>
        <img class="products__img" src="Assets/red.jpg" alt="product image" />
      </div>
      <div>
        <img class="products__img" src="Assets/yellow.jpg" alt="product image" />
      </div>
      <div>
        <img class="products__img" src="Assets/green.jpg" alt="product image" />
      </div>
      <div>
        <img class="products__img" src="Assets/orange.jpg" alt="product image" />
      </div>
      <div>
        <img class="products__img" src="Assets/purple.jpg" alt="product image" />
      </div>
    </section>

    <template id="cart-item-template">
      <div class="cart-item">
        <div class="cart-item__img-container">
          <img class="cart-item__img w-100 block" alt="item image" src="Assets/blue.jpg" />
          <button class="cart-item__close-btn">&times;</button>
        </div>
        <div class="cart-item__desc">
          <div class="cart-item__name"></div>
          <div class="cart-item__quantity"></div>
          <div class="cart-item__price"></div>
        </div>
      </div>
    </template>
  </body>
</html>

store.html

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" type="module"></script>
    <title></title>
  </head>
  <body>
    <header class="header">
      <div class="container header__container">
        <nav class="menu">
          <a class="menu__link" href="index.html">Home</a>
          <a class="menu__link menu__link--active" href="store.html">Store</a>
          <a class="menu__link" href="team.html">Team</a>
        </nav>
        <button class="cart__btn">
          <img src="Assets/icon-cart-white.svg" alt="cart icon" />
          <span class="cart__quantity"></span>
        </button>
        <div class="cart__items-wrapper">
          <div class="cart__items"></div>
          <div class="cart__total-wrapper">
            <span>TOTAL</span>
            <span class="cart__total">$0.00</span>
          </div>
        </div>
      </div>
    </header>
    <section class="container items"></section>
    <template id="item-template">
      <div class="item">
        <img class="item__img" src="Assets/blue.jpg" alt="product image" />
        <small class="item__category">PRIMARY COLOR</small>
        <strong class="item__name">Blue</strong>
        <small class="item__price">$16.00</small>
        <button class="item__add-btn">Add To Cart</button>
      </div>
    </template>
    <template id="cart-item-template">
      <div class="cart-item">
        <div class="cart-item__img-container">
          <img
            class="cart-item__img w-100 block"
            alt="item image"
            src="Assets/blue.jpg"
          />
          <button class="cart-item__close-btn">&times;</button>
        </div>
        <div class="cart-item__desc">
          <div class="cart-item__name"></div>
          <div class="cart-item__quantity"></div>
          <div class="cart-item__price"></div>
        </div>
      </div>
    </template>
  </body>
</html>

script.js

import setupStore from "./store.js";
import setupShoppingCart from "./shoppingCart.js";
setupStore();
setupShoppingCart();

shoppingCart.js

import formatCurrency from "./util/formatCurrency.js";
const cart_items_wrapper = document.querySelector(".cart__items-wrapper");
const cart_items = document.querySelector(".cart__items");
const cart_btn = document.querySelector(".cart__btn");
const cart_quantity = document.querySelector(".cart__quantity");
const cart_total = document.querySelector(".cart__total");
const cart_item_template = document.querySelector("#cart-item-template");
let shoppingCart = JSON.parse(localStorage.getItem("cart-items")) || [];
let items = []; 

async function fetchData() {
  try {
    const response = await fetch("./items.json");
    items = await response.json();
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

export default async function setupShoppingCart() {
  await fetchData(); // ✅ Ensures data is fetched first
  renderCartItems();
  cart_btn.addEventListener("click", () =>
    cart_items_wrapper.classList.toggle("cart__items-wrapper--active")
  );

  cart_items.addEventListener("click", e => {
    if (!e.target.matches(".cart-item__close-btn")) return;
    const cart_item_id = e.target.closest(".cart-item").id;
    removeFromCart(cart_item_id);
    renderCartItems();
    saveCart();
  });
  
}

export function addToCart(id) {
  const existing_item = shoppingCart.find(entry => entry.id == id);
  if (existing_item) existing_item.quantity++;
  else shoppingCart.push({ id: id, quantity: 1 });
  renderCartItems();
  saveCart();
}

function renderCartItems() {
  cart_items.innerText = "";
  shoppingCart.forEach(entry => {
    const item = items.find(item => item.id == entry.id);
    const cart_item_node = cart_item_template.content.cloneNode(true);
    const cart_item = cart_item_node.querySelector(".cart-item");
    const cart_item_img = cart_item.querySelector(".cart-item__img");
    const cart_item_name = cart_item.querySelector(".cart-item__name");
    const cart_item_quantity = cart_item.querySelector(".cart-item__quantity");
    const cart_item_price = cart_item.querySelector(".cart-item__price");
    cart_item.id = item.id;
    cart_item_img.src = item.imageSrc;
    cart_item_name.innerText = item.name;
    if (entry.quantity > 1) cart_item_quantity.innerText = `x${entry.quantity}`;
    cart_item_price.innerText = formatCurrency(item.priceCents / 100);
    cart_items.appendChild(cart_item);
  });
  const total_cents = shoppingCart.reduce((sum, entry) => {
    const item = items.find(item => item.id == entry.id);
    return (item.priceCents + sum) * entry.quantity;
  }, 0);
  cart_total.innerText = formatCurrency(total_cents / 100);
  cart_quantity.classList.add("cart__quantity--active");
  cart_quantity.innerText = shoppingCart.length;
  if (shoppingCart.length < 1) {
    hideCart();
    cart_quantity.classList.remove("cart__quantity--active");
  }
}

function saveCart() {
  localStorage.setItem("cart-items", JSON.stringify(shoppingCart));
}

function removeFromCart(id) {
  shoppingCart = shoppingCart.filter(entry => entry.id != id);
}

function hideCart() {
  cart_items_wrapper.classList.remove("cart__items-wrapper--active");
}

store.js

import { addToCart } from "./shoppingCart.js";
import formatCurrency from "./util/formatCurrency.js";
const item_template = document.querySelector("#item-template");
const items_container = document.querySelector(".items");
let items = []; // Declare an empty array
async function fetchData() {
  try {
    const response = await fetch("./items.json");
    items = await response.json();
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

export default async function setupStore() {
  if (items_container == null) return;
  await fetchData();
  items.forEach(renderStoreItem);
  document.addEventListener("click", e => {
    if (!e.target.matches(".item__add-btn")) return;
    const item_id = e.target.parentElement.id;
    addToCart(item_id);
  });
}

function renderStoreItem(item) {
  const storeItemTemplate = item_template.content.cloneNode(true);
  const storeItem = storeItemTemplate.querySelector(".item");
  storeItem.id = item.id;
  const img = storeItem.querySelector(".item__img");
  const category = storeItem.querySelector(".item__category");
  const name = storeItem.querySelector(".item__name");
  const price = storeItem.querySelector(".item__price");
  img.src = item.imageSrc;
  category.innerText = item.category;
  name.innerText = item.name;
  price.innerText = formatCurrency(item.priceCents / 100);
  items_container.append(storeItem);
}

items.json

[
  {
    "id": 1,
    "name": "Red",
    "category": "Primary Color",
    "priceCents": 1600,
    "imageSrc": "Assets/red.jpg"
  },
  {
    "id": 2,
    "name": "Yellow",
    "category": "Primary Color",
    "priceCents": 2100,
    "imageSrc": "Assets/yellow.jpg"
  },
  {
    "id": 3,
    "name": "Blue",
    "category": "Primary Color",
    "priceCents": 1200,
    "imageSrc": "Assets/blue.jpg"
  },
  {
    "id": 4,
    "name": "Orange",
    "category": "Secondary Color",
    "priceCents": 1800,
    "imageSrc": "Assets/orange.jpg"
  },
  {
    "id": 5,
    "name": "Green",
    "category": "Secondary Color",
    "priceCents": 1600,
    "imageSrc": "Assets/green.jpg"
  },
  {
    "id": 6,
    "name": "Purple",
    "category": "Secondary Color",
    "priceCents": 2100,
    "imageSrc": "Assets/purple.jpg"
  },
  {
    "id": 7,
    "name": "Light Gray",
    "category": "Grayscale",
    "priceCents": 1200,
    "imageSrc": "Assets/lightGrey.jpg"
  },
  {
    "id": 8,
    "name": "Dark Gray",
    "category": "Grayscale",
    "priceCents": 1600,
    "imageSrc": "Assets/darkGrey.jpg"
  }
]

style.css

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: Sans-Serif, "Courier New";
}

.container {
  padding: 0 20px;
  max-width: 1024px;
  margin: auto;
}
body {
  margin-top: 4rem;
}
.menu {
  display: flex;
  justify-content: center;
  gap: 1rem;
  padding: 1rem 20px;
}

.menu__link {
  text-decoration: none;
  color: gray;
}

.menu__link--active {
  text-decoration: 1.5px solid underline lightblue;
  text-underline-offset: 4px;
}

.intro-sec {
  text-align: center;
  line-height: 1.4;
  margin-top: 2rem;
}

h2 {
  margin-bottom: 10px;
}

.team-sec {
  display: grid;
  gap: 1rem;
  margin: 2rem auto;
}

.team-card {
  border: 1px solid silver;
  border-radius: 5px;
  padding: 1rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.ps {
  margin: 2rem 0;
}

.products {
  display: grid;
  gap: 1rem;
  margin-bottom: 2rem;
}

.products__img {
  width: 100%;
  display: block;
}

.items {
  margin: 2rem auto;
  display: grid;
  gap: 2rem;
}

.item {
  position: relative;
}

.item__img {
  width: 100%;
  border-radius: 3px;
}

.item__name {
  display: block;
  margin: 5px 0;
}

.item__add-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  padding: 10px;
  background: skyblue;
  color: white;
  border: none;
  font-weight: bold;
  border-radius: 3px;
  cursor: pointer;
}

.header {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 2;
  background: white;
}

.cart__btn {
  border: none;
  background: #2bafff;
  width: 35px;
  height: 35px;
  border-radius: 50px;
  display: inline-grid;
  place-items: center;
  cursor: pointer;
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.cart__quantity {
  color: white;
  background: orange;
  width: 20px;
  height: 20px;
  border-radius: 50px;
  position: absolute;
  bottom: -7px;
  right: -7px;
  display: none;
  place-items: center;
}

.cart__quantity--active {
  display: inline-grid;
}

.cart__items-wrapper {
  width: 180px;
  position: absolute;
  background: white;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.211);
  right: 20px;
  top: 110%;
  display: none;
}

.cart__items-wrapper--active {
  display: block;
}

.cart__items {
  padding: 12px;
  max-height: 60vh;
  overflow-y: scroll;
}

.cart__total-wrapper {
  padding: 12px;
  border-top: 1px solid silver;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
}

.w-100 {
  width: 100%;
}

.block {
  display: block;
}

.cart-item:not(:last-child) {
  margin-bottom: 1rem;
}

.cart-item__img-container {
  position: relative;
  border-radius: 5px;
  overflow: hidden;
}

.cart-item__close-btn {
  background: black;
  position: absolute;
  border: none;
  top: 0;
  right: 0;
  color: white;
  width: 22px;
  height: 22px;
  font-size: 1rem;
  cursor: pointer;
}

.cart-item__desc {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.cart-item__quantity {
  font-size: 0.8rem;
  margin-left: 2px;
}

.cart-item__price {
  margin-left: auto;
}

@media (min-width: 734px) {
  .team-sec {
    grid-template-columns: 1fr 1fr;
  }
  .items {
    grid-template-columns: 1fr 1fr;
  }
}
@media (min-width: 986px) {
  .team-sec {
    grid-template-columns: 1fr 1fr 1fr;
  }
  .products {
    grid-template-columns: repeat(4, 1fr);
  }
  .products div:nth-child(3) {
    grid-column: 3 / 5;
    grid-row: 1 / 3;
  }
  .products div:nth-child(4) {
    grid-column: 1 / 3;
    grid-row: 2 / 4;
  }
  .items {
    grid-template-columns: 1fr 1fr 1fr;
  }
}

r/programminghelp • • Dec 06 '22

JavaScript Can't get output from the function.

1 Upvotes
Could someone help i can't seem to get the ouput i want from this mygreeting function. Can someone tell me whats wrong with the function. 


// Four characteristics

let fictionalDog = {

  name: "Bandit",

  breed: "Terrier",

  TvProgram: "Jonny Quest",

  notes: "Jonny's dog; about a boy who accompanies his father on extraordinary adventures",




}


fictionalDog.mysound = "A dog might say, no one will believe you",  // New Property after object is created


 // Access Object Values

document.write("My name is ");
document.write(fictionalDog.name);
document.write(",");
document.write(" I am a ") ;
document.write(fictionalDog.breed);
document.write(" Dog!, ");
document.write("I Played a part in the tv show ");
document.write(fictionalDog.TvProgram);
document.write(".");
document.write(" I was ");
document.write(fictionalDog.notes);



// Object Constructor

function MyDogConst(){

  this.name = "Bandit";

  this.breed = "Terrier";

  this.TvProgram = "Jonny Quest";

  this.notes = "Jonny's dog; about a boy who accompanies his father on extraordinary adventures";

  this.canTalk = "Yes";

  this.myGreeting=function(){console.log('Hello the dogs name is ${this.name} and his breed is ${this.breed}')}




}

r/programminghelp • • Jul 24 '24

JavaScript Node.js Best Buy API

1 Upvotes

I'm developing a simple website using NodeJS for a friend of mine, and its mean to let them input a SKU for a product at Best Buy, and using their API, tell them what stores it is sold at in the U.S.

I've had some success withe basic attributes. For example:

const bestBuyAPI = require('bestbuy')('myAPIKey');
bestBuyAPI.products(6540612,{show:'sku,name,condition,salePrice,inStoreAvailability,inStorePickup'}).then(function(data){
    console.log(data);
});

But I can't seem to find a way to print the available stores for any products.

I tried using this Stack Overflow thread but due to the age of it, there's not really anything functional

If anyone could help me find a way to list all the available stores for a specific SKU, that'd be great, thanks!

Here's the API's Documentation btw:
https://bestbuyapis.github.io/api-documentation

r/programminghelp • • Nov 03 '25

JavaScript How to check for collisions between sprites in an array

1 Upvotes

Hey Y'all,

I'm working on essentially a game engine in javascript and I wanted to see If you guys had any advice on detecting collisions between all sprites in an array.

currently, I'm using bounding circle and box collision detection and planning to double traverse every element in the array.

function updateChunk(chunk) {
    //get chunck objects
    objArr = [];


    for(let key in level.objectHash){
        for(let objInx = 0; objInx < level.objectHash[key].length(); objInx++){
            if(level.objectHash[key][objInx].chunk == chunk){
                objArr.push(level.objectHash[key][objInx].chunk);
            }
        }
    }


    //scout change
    for(let chunkArr = 0; chunkArr < objArr.length(); chunkArr++){
        //temp update pos
        objArr[chunkArr].sprite.x += objArr[chunkArr].sprite.dx;
        objArr[chunkArr].sprite.y += objArr[chunkArr].sprite.dy;
          //second traversal here
        objArr[chunkArr].sprite.x -= objArr[chunkArr].sprite.dx;
        objArr[chunkArr].sprite.y -= objArr[chunkArr].sprite.dy;
    }
}

but obviously, that's super slow. I was wondering if you guys knew any tricks or articles to optimize this process.

Thanks Y'all!

r/programminghelp • • Aug 13 '25

JavaScript Language translation

1 Upvotes

I’m working on a personal project and I’m reaching an important stage where I need to implement an interface with an external system (which has no documentation). There’s an open source tool (MIT license so no licensing issues) that has this functionality (along with many others, obviously) but it’s developed in Kotlin while my entire project is in TypeScript. Doing all the reverse engineering and translation to TypeScript would be months of work. I tried with Claude Code (by throwing it directly at the task or asking it to do file-by-file translation) but it wasn’t conclusive despite numerous attempts. Do you know of a tool or technique to take functionality written in another language (Kotlin -> TS) and integrate it into my project?

r/programminghelp • • May 13 '24

JavaScript My javascript won't load

1 Upvotes

Hey, I'm currently trying to host a maze game via firebase and my javascript won't load.
When I press the "start game" button nothing happens, no error messages are seen in the console but the script lines are greyed out. I have searched google and asked llms but to no avail. Would love to get some pointers. You can see the code here: https://github.com/thedfn/Maze

r/programminghelp • • Jan 30 '24

JavaScript [js] [css] Auto scroll function shows a part of previous image on left with current image.

1 Upvotes

https://jsfiddle.net/Ds9999/3nk0zxg1/6/

I have been playing around in jsfiddle and I really cannot figure it out why am I seeing a part of remaining image on the left of the current image and the part of image increases gradually with each image scrolling towards rightside.