updating html when a variable changes

I have a code for a clicker game i am working on and i need the displayed html to update when the variable changes

This is my javascript:

var carparts = 0
document.getElementById("karpartz").innerHTML = carparts;

function onButtonClick() {
  carparts = carparts + 1
  alert(carparts)}

const button = document.querySelector('button');
button.addEventListener('click', onButtonClick);



and this is my html:

<p id="karpartz"></p>
<button>
button
</button>
<html>
<head>
  <script type="text/javascript">
  </script>
</head>

<body>
    <h1>
      <script type="text/javascript">
        document.write(karpartz)
      </script>
    </h1>
</body>
</html>

how do i get this to work if it even possible?

i cant find anything to help me and i am super stuck. please help.

need guidance for ML for web dev

Hi I’m new to ICT and I want to build a personal website but all the tutorials keep talking about coding. I think coding is on its way out because of chatgpt so I’d like to do it with machine learning instead, can someone guide me with this or do it for me?

Watched tutorials on JavaScript

Javascript: Augment a standard class without global prototype changes

A classic “bad idea” in JS is to alter the prototypes of inbuilt types:

Array.prototype.last = function() { return this[this.length - 1] }; 
[1,2,3].last() // 3

In ES6 we can extend the inbuilt Array type:

class MyArray extends Array {
  last() {
    return this[this.length - 1];
  }
}

But there’s no great way to add these functions without copying:

a = [1, 2, 3]
b = new MyArray(...a);
// [1, 2, 3]
b === a 
// False

We can update the object’s prototype:

a = [1, 2, 3]
Object.setPrototypeOf(a, MyArray.prototype);
a.last() // 3
Object.setPrototypeOf(a, Array.prototype);
a.last() // TypeError

However, MDN says:

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine.

Helper functions or container classes can help, but their syntax is unwieldy:

ArrayHelper.last(a); // 3
MyArrayWrapper(a).last(); // 3
MyArrayWrapper.get(0); // Ugh, we lose []-based indexing.

The ideal solution would be something like:

a = [1, 2, 3];
b = asMyArray(a);
b.last(); // 3
a.last(); // TypeError

// But avoid doing a copy, and have both objects reference the same memory:
b[0] = 10; 
a[0] == 10; // true

or, if it’s easier

a = [1, 2, 3];
applyMyArrayPrototype(a);
a.last(); // 3
a.dropMyArrayPrototype();
a.last(); // TypeError

Is there a way to achieve this in JS?

Ensuring Type Safety in function signature: Matching values

I want to setup a config object that has a format method.

I can not seem to get type checking on the argument for the format method

export interface Config<D, ConfigId extends keyof D> {
  id: ConfigId
  format?: (value: D[ConfigId]) => any
}

type Data = {testA: number, testB: string}

const configObjs: readonly Config<{testA: number, testB: string}, keyof Data>[] = [
  {
    id: 'testA',
    format: (value) => {
      return value
    },
  },

]

I have tried a good bit. Can not get anything working.

I am expecting/wanting the arg in the format method in the above example to only be a number.

Here is a typescript playground idk how long they last but:
https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgYQiXQQHMAeAEQBoCiTSBJAEzlFSWYGc4BrYAJ4R0cSgD44AbwBQcRMwBcdYmRay46aAFtMMAPxKAFADdMAGwCuwJZQDahFU2YBdAJRwAvBMxIB0gL7S0jACYHiUupieUqhcMACCSkgWWgBGaLSxMABCSnFQyKSB0thEcXCljgDyqQBWXEpQwJjMRGYCygzkklmJcMlpGXBZuXD5hf60-EIiETCYYrbO0bbqMnJyCIpwAOS9O9TqcppQOjBGppbA7l5SRxtNMBZQSHCXVveT6l-SztJAA

How to provide callbacks to a Custom Element

I decided to try my hand at creating a native web component by writing a Custom Element.

export default class DropDown extends HTMLElement {
...

Once I got everything in place, it seemed to be working fine. But then I decided to add some callback hooks so the application could respond to events on the component.

The logical place to add them is in the constructor, right?

 /**
   * 
   * @param {Object} callbacks
   * @param {Function} callbacks.itemSelected 
   * @param {Function} callbacks.dropDownClicked
   */
  constructor(callbacks = {}) {
    super();
    if (callbacks) this.#callbacks = callbacks;
  }

  #handleItemSelected(selection) {
    console.log('handleItemSelected()');
    if (this.#callbacks.itemSelected) this.#callbacks.itemSelected(this, selection);
    if (this.#displaySelection) this.#valuePara.textContent = selection;
  }

And then in my application code:

function demoHandler(thisVal, selection) {
    console.log('demoHandler ' + thisVal + ' ' + selection);
}

new DropDown({ itemSelected: demoHandler });

But the callback wasn’t getting executed. I figured out that this.#callbacks was empty. So I logged the various method/function calls. Here’s the order they’re executed in:

constructor()
attributeChangedCallback()
connectedCallback()
constructor()
<user click>
handleItemSelected()

Wow. constructor() is called by the Custom Element framework. When my app code calls it again later, it’s pointless because the object my app constructs isn’t the object being used by the framework. Moreover, there’s no way for the application to get the object ref from the framework’s instantiation. Without that object reference, I don’t know how I can pass in callback functions for the object to execute.

How can I add these callbacks to my object?

Mock the locale used by Number.toLocaleString in jest?

I’m trying to write some unit tests on a function that calls Number.toLocaleString() with no arguments (which causes it to use the browser’s language as the locale).

I need to be able to mock the browser locale used by this function, so I can unit test how it works for different locales.

I tried mocking window.navigator.language, but I guess the toLocaleString implementation doesn’t directly read this value, so it doesn’t work:

let windowSpy: jest.SpyInstance;
beforeEach(() => {
  windowSpy = jest.spyOn(global, 'window', 'get');
});
afterEach(() => windowSpy.mockRestore());

it('should format correctly (fr-CA)', () => {
  windowSpy.mockImplementation(() => ({
    navigator: {
      language: 'fr-CA',
      languages: ['fr-CA'],
    },
  }));
  const result = 12345678.9.toLocaleString();
  expect(result).toEqual('12 345 678,9');
});

The above test fails because it returns en-US format:

    Expected: "12 345 678,9"
    Received: "12,345,678.9"

What do I need to do to mock the browser’s locale for Number.toLocaleString()?

Page crashes with tabulator when maxHeight is set with only 47 records

I’m running into an issue with Tabulator where I set maxHeight on my datatable but the page runs at 100% CPU and eventually crashes, profiler in Chrome crashes as well but I was able to get this stack trace attached. I ran into this issue when I started adding more data to the app. I’ve only got 47 records for one of the pages and it crashes. I’ve also only had it use the “name” column and commented out all other columns, but still the same issue.

I’ve tried to reproduce this in js fiddle, but I can’t. Any datatable in my app that uses maxHeight and has over 20 records will crash the page. If I set maxHeight to 600px it works fine. Also using height instead of maxHeight works fine as well. But I would prefer to use maxHeight so the datatable grows to fill the page.

Here’s my code to create one of my datatables.

  renderTabulator(url: string) {
    this.table = new Tabulator(this.element, {
      ajaxURL: url,
      movableColumns: true,
      layout: "fitDataFill",
      maxHeight: `calc(100vh - ${this.tableDistanceToTop + 30}px)`,
      placeholder: "No Data Available",
      columnDefaults: {
        vertAlign: "middle",
      },
      columns: [
        {
          field: "actions",
          title: "",
          formatter: "html",
          headerSort: false,
          headerHozAlign: "center",
          hozAlign: "center"
        },
        { field: "name", title: "Name", headerFilter: "input", width: 200 },
        { field: "address", title: "Address", headerFilter: "input", width: 250 },
        { field: "suburb", title: "Suburb", headerFilter: "input" },
        { field: "state", title: "State", headerFilter: "input", headerHozAlign: "center", hozAlign: "center" },
        { field: "postcode", title: "Postcode", headerFilter: "input", headerHozAlign: "right", hozAlign: "right" },
        { field: "area", title: "Area", headerFilter: "input" },
      ],
    });
  }

Any ideas what I’m doing wrong?

stacktrace

Im trying to figure out why my code exceeds 4 seconds in certain cases

I’m doing a test on codesignal. safe to say I’m going to fail this question, it’s my only question left and I spent all my time on it. time is running out I think it should be alright to ask for help at this point as I don’t know what else to do. Here is my code and the comments explain what the goal is. The goal is to figure out the greatest length you can cut the ribbons(a) to get at least (k) pieces.
My main issue is for certain hidden tests, the time limit of 4 seconds is exceeded. but when I run performance.now() all of the visible tests are below 0.09 seconds at most. I can’t figure out why.

function solution(a, k) {
  // the logic here is to determine the biggest size (in length) you can cut the 
  // ribbons(a) into atleast(k) amount of pieces.
  
  // for example a = [1,2,3,4,5]; k = 5 lets use 1 length.
  // 1 - 1 = 0
  // 2 - 1 - 1 = 0
  // 3 - 1 -1 -1 = 0
  // 4 - 1 - 1 -1 -1 = 0
  // 5 - 1 - 1 - 1 -1 -1 = 0, this results in 15 pieces. lets narrow it down with 2
  // 1 - 2 = -1 (this will have to be avoided somehow. for example if a[i] > length)
  // 2 - 2 = 0
  // 3 - 2 = 1 (rule will stop it here thanks to previous example)
  // 4 - 2 -2 = 0
  // 5 - 2 - 2 = 1 (rule will stop it here thanks to previous example)
  //
  // this will result in 6 pieces. can we narrow it down further? lets try 3.
  // we can skip 1 & 2 as the rule will do so too.
  // 3 - 3 = 0
  // 4 - 3 = 1
  // 5 - 3 = 2 this results in 3 pieces. this is not enough pieces. we need a rule in place to invalid this, if the number of pieces is not greater or equal to k.
  
  // we will use a loop test to give us the greatest number, while making a rule that it must be greater than k.
  // then we return the value of test

  let l = 1; // (the length)
  let test = 1000000000;
  let answer;
  while (l < 1000000000) {
    testArr = a.slice();
    let pieces = 0;
    for (i = 0; i < testArr.length; i++) {
      testArr[i] /= l;
      pieces += parseInt(testArr[i]);
    }

    if (pieces < k) {
      l = 1000000000;
    } else {
      if (pieces <= test) {
        test = pieces;
        answer = l;
        console.log(`${l}in for ${pieces} pieces`);
      }
      l++;
    }
  }
  var endTime = performance.now();
  console.log(`it look ${endTime} milliseconds`);
  return answer;
}

the constraints of the problem are between 1 & 10 to the 9th power.
I used performance.now() to test the speed, and every visible test i below 0.09 seconds. so im lost why certain hidden test exceed the time limit of 4 seconds.
this code works for all of the visible test, but there are hidden test that are not passing, and i cant figure out for the life of me why. is it because its too slow? what can i remove or replace to speed it up IF thats the issue? or is there another issue i am blind too?

Im not exactly sure, as the hidden test are well hidden. But i could say i was expecting my code to be faster?

How to prevent the page from loading until a script in the head with promises resolve

I have an external asynchronous script needs to finish executing before the page loads. To my understanding (from this thread), the default behaviour before the page starts to load is that it finishes rendering the head tag’s contents, and if it includes a script, it finishes parsing that too, before proceeding to load the page. However, I could be wrong, but this seems to not apply to asynchronous scripts.

How could I make this example asynchronous script below finish executing (and all promises finishing) before the page starts to load?

The page, including the script:

Playground: https://playcode.io/1782092

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>p {color: white}</style>

    <script>
  // Function to create a fake promise that resolves after 3 seconds
  async function fakePromise() {
    return new Promise(function(resolve, reject) {
      setTimeout(resolve, 3000); // Resolve after 3 seconds
    });
  }

  // Use async/await to wait for the fake promise to resolve
  async function applyStyle() {
    await fakePromise();

    // Create a <style> element
    var styleElement = document.createElement('style');

    // Define the CSS rule
    var css = "p { color: pink !important; }";

    // Add the CSS rule to the <style> element
    styleElement.appendChild(document.createTextNode(css));

    // Insert the <style> element into the <head> of the document
    document.head.insertBefore(styleElement, document.head.firstChild);
  }

  // Call the function to apply the style
  applyStyle();

  // *** in the REAL app, this script would just have empty contents and have a src attribute ***
</script>

  </head>
  <body>
    
    <p>testing</p>

  </body>
</html>

As you can see, the example ‘testing’ text changes colour after 3 seconds, but the problem is that this happens after the page has loaded.

If this is not possible, how else could I, for example, redirect to another page after the asynchronous script finishes but before the page starts to load?

“VS Code extension in Javascript not working”

I have been attempting to implement a simple VSCode extension in JavaScript for some time now.

I have completed the setup using yo code.
Then, I installed the necessary dependencies using npm install.
However, when I try to start a debug session by pressing F5, a new window appears.
During the debug session, I can see that my extension has started, I suppose.
But in the new window, I cannot find the “Hello World” command.

Am I missing something?

Why doesn’t detect-gpu detect my video card

I am using detect-gpu in a javascript project. On my mac it works fine. But my PC has an Nvidia RTX 3080 and intel graphics. When I use getGPUTier() on my pc it returns the intel graphics. I have set all the setting to default to the graphics card in the Nvidia settings, Upgraded the drivers, and even disabled the intel graphics adaptor. But no matter what I do, it does not return the 3080.

How to set CSS properties of child html tag with typescript

I have the following HTML:

<li id="test">
    <span>Anything</span>
    <button>
        <svg>
            <use xlink:href="assets/icon/sprite.svg#icon-check"></use>
        </svg>
    </button>
</li>

And I have a function that changes the bottom color of the li tag (and works properly)

private setColor(): void {
  const rowId = 'test'; 

  const row = document.getElementById(rowId) as HTMLElement;

  const colorToSet = '#33be09';
  row.style.borderBottomColor = colorToSet;
}

My issue is that I also want to change the color of the svg, but I can’t access the svg in my function. I’ve tried the children function, but I don’t know how to access specifically the svg. How can I do this?

how do i fix these errors in my expo/ react native app(im new to react)

ReferenceError: Property ‘expect’ doesn’t exist, js engine: hermes
ERROR Invariant Violation: “main” has not been registered. This can happen if:

  • Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
  • A module failed to load due to an error and AppRegistry.registerComponent wasn’t called., js engine: hermes

i tried bundling my app on my iphone through expo go