Converting Three.js function from a sphere to a torus

This function listed below shows a sphere of starbursts. I cant seem to figure out how to make this same function but generate a torus of starbursts instead of a sphere.
The parameters would include the toroids major and minor radii.

Here is what the final outcome should look like:
Final outcome

let camera, scene, renderer;
let cameraControls;
let clock = new THREE.Clock();
let root = null, sphereRadius;



function createSceneA() {
    sphereRadius = 15;
    root = starburstsOnSphereA(400, sphereRadius, 100, 1)
    scene.add(root);
}


function starburstsOnSphereA(nbrBursts, sphereRadius, maxRays, maxRad) {
    let root = new THREE.Object3D();
    for (let i = 0; i < nbrBursts; i++) {
        let mesh = starburstA(maxRays, maxRad);
        let p = getRandomPointOnSphere(sphereRadius);
        mesh.position.set(p.x, p.y, p.z);
        root.add(mesh);
    }
    return root;
}

function starburstA(maxRays, maxRad) {
    let rad = 1;   // had been rad = 10?????
    let origin = new THREE.Vector3(0, 0, 0);
    let innerColor = getRandomColor(0.8, 0.1, 0.8);
    let black = new THREE.Color(0x000000);
    let geom = new THREE.Geometry();
    let nbrRays = getRandomInt(1, maxRays);
    for (let i = 0; i < nbrRays; i++) {
        let r = rad * getRandomFloat(0.1, maxRad);
        let dest = getRandomPointOnSphere(r);
        geom.vertices.push(origin, dest);
        geom.colors.push(innerColor, black);
    }
    let args = {vertexColors: true, linewidth: 2};
    let mat = new THREE.LineBasicMaterial(args);
    return new THREE.Line(geom, mat, THREE.LineSegments);
}




function animate() {
    window.requestAnimationFrame(animate);
    render();
}

let controls = new function() {
    this.nbrBursts = 400;
    this.burstRadius = 1.0;
    this.maxRays = 100;
    this.Go = update;
}

function initGui() {
    let gui = new dat.GUI();
    gui.add(controls, 'nbrBursts', 5, 2000).step(5).name('Nbr of bursts');
    gui.add(controls, 'burstRadius', 0.1, 5.0).name('Burst radius');
    gui.add(controls, 'maxRays', 5, 200).name('Max nbr of rays');
    gui.add(controls, 'Go');
}

function update() {
    let nbrBursts = controls.nbrBursts;
    let burstRadius = controls.burstRadius;
    let maxRays = controls.maxRays;
    if (root)
        scene.remove(root);
    root = starburstsOnSphereA(nbrBursts, sphereRadius, maxRays, burstRadius);
    scene.add(root);
}



function render() {
    let delta = clock.getDelta();
    cameraControls.update(delta);
    renderer.render(scene, camera);
}


function init() {
    let canvasWidth = window.innerWidth;
    let canvasHeight = window.innerHeight;
    let canvasRatio = canvasWidth / canvasHeight;

    scene = new THREE.Scene();

    renderer = new THREE.WebGLRenderer({antialias : true, preserveDrawingBuffer: true});
    renderer.gammaInput = true;
    renderer.gammaOutput = true;
    renderer.setSize(canvasWidth, canvasHeight);
    renderer.setClearColor(0x000000, 1.0);

    camera = new THREE.PerspectiveCamera( 40, canvasRatio, 1, 1000);
    camera.position.set(0, 0, 40);
    camera.lookAt(new THREE.Vector3(0, 0, 0));
    cameraControls = new THREE.OrbitControls(camera, renderer.domElement);

}


function addToDOM() {
    let container = document.getElementById('container');
    let canvas = container.getElementsByTagName('canvas');
    if (canvas.length>0) {
        container.removeChild(canvas[0]);
    }
    container.appendChild( renderer.domElement );
}



init();
createSceneA();
initGui();
addToDOM();
animate();
function getRandomPointOnSphere(rad) {
  rad = rad || 1.0;
  var theta = Math.random() * 2 * Math.PI;
  var phi = Math.acos(2 * Math.random() - 1);
  var x = rad * Math.cos(theta) * Math.sin(phi);
  var y = rad * Math.sin(theta) * Math.sin(phi);
  var z = rad * Math.cos(phi);
  return new THREE.Vector3(x, y, z);
}

Using the older version of three js: Three.js code

JavaScript ListItem onClick issue

I’m working on a web-app in HTML and JS and I need to catch the clicks on each listItem of a list.
The list is dynamically created in a for-loop as follows:

var i = document.createElement("li");
i.innerHTML = "something"
uList.appendChild(i);

How can I make listItems clickable or catch clicks on each of them separately (get the specific item clicked)?
I’ve tried adding an eventListener on the list, and then isolate the target of the event (click). The problem is that this would count as many clicks as the size of the list.

How to set up conditionals in setup function in Vue 3 Composition API

I am attempting to build a basic Vue 3 app with composition API that enables the user to guess an audible musical note by selecting buttons displaying 4 randomly shuffled musical notes from a selection of 7 notes (A,B,C,D,E,F,G). The first part of the setup function, under // Handle Audio passes 7 musical notes (imported as mp3 clips in assets) into an array called audioArray. The notes in audioArray are then shuffled in shuffleAudio, then passed to audio.value. The audio is played when the user clicks “click for audio”, and reshuffled with the onBeforeMount life cycle hook. Meanwhile, under // handleLetters, each of the four buttons are configured to display a letter corresponding to a musical note, which are shuffled when shuffleLetter is called by onBeforeMount.

I am now trying to get the buttons to trigger “correct” and “incorrect” messages when the user selects either the correct or incorrect note. To do this, I tried setting up the buttons with click events (ex. handleSelectOne, handleSelectTwo…etc.). For example, in handleSelectOne, if the button note displayed is “A” and the musical note playing is noteA, then the message displayed is ‘CORRECT’ when the user taps the “A” button, else ‘INCORRECT’. However, I tried putting a breakpoint on handleSelectOne, but the event isn’t triggered upon selecting A when noteA is played. Meanwhile, I am not sure if my conditional is setup correctly. How can I set up the logic in handleSelectOne to respond correctly if the button letter is A and corresponds to the note being played?

Here is my code so far:

template

<template>
  <div div class="flex justify-center">
    <button @click="handleAudio">Click for Audio</button>
  </div>
  <div class="flex justify-center">
    <button @click="handleSelectOne">{{ letters.letterDisplayOne }}</button>
    <button @click="handleSelectTwo">{{ letters.letterDisplayTwo }}</button>
    <button @click="handleSelectThree">{{ letters.letterDisplayThree }}</button>
    <button @click="handleSelectFour">{{ letters.letterDisplayFour }}</button>
    <button @click="handleSelectNone">None</button>
  </div>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

script

<script>
import { ref, reactive, onBeforeMount } from 'vue';
const noteA = require("../assets/note-a.mp3")
const noteB = require("../assets/note-b.mp3")
const noteC = require("../assets/note-c.mp3")
const noteD = require("../assets/note-d.mp3")
const noteE = require("../assets/note-e.mp3")
const noteF = require("../assets/note-f.mp3")
const noteG = require("../assets/note-g.mp3")

export default {
  name: 'Button',
  components: {},
  setup() {

// Handle Audio
    const audioArray = ref([noteA, noteB, noteC, noteD, noteE, noteF, noteG])
    const audio = ref(audioArray.value)

    const shuffleAudio = () => {
      audioArray.value = audioArray.value.sort(() => 0.5 - Math.random())
    }
    
    const handleAudio = () => {
      audio.value = new Audio(audioArray.value[0]);
      audio.value.play()
      console.log(audioArray.value)
    }

// Handle Letters
    const letters = reactive({
      letterDisplayOne: '',
      letterDisplayTwo: '',
      letterDisplayThree: '',
      letterDisplayFour: ''
    })

    const letterArray = ref(['A','B','C','D','E','F','G'])

    const shuffleLetter = () => {
      letterArray.value = letterArray.value.sort(() => 0.5 - Math.random())
    }

    const handleLetterArray = () => {
      letters.letterDisplayOne = letterArray.value[0]
      letters.letterDisplayTwo = letterArray.value[1]
      letters.letterDisplayThree = letterArray.value[2]
      letters.letterDisplayFour = letterArray.value[3]
    }

// Handle message
    const message = ref('')

    const handleSelectOne = () => {
      if (letters.letterDisplayOne === 'A' && audio.value === audioArray.value[noteA]) {
        message.value = 'CORRECT!!!!'
      } else {
        message.value = 'INCORRECT!!!!'
      }
    }

    const handleSelectTwo = () => {
      // functionality for handleSelectTwo
    }

    const handleSelectThree = () => {
      // functionality for handleSelectThree
    }

    const handleSelectFour = () => {
      // functionality for handleSelectFour
    }

    const handleSelectNone = () => {
      // functionality for handleSelectNone
    }

    onBeforeMount(() => {
      shuffleAudio()
      shuffleLetter()
      handleLetterArray()
    })

    return {
      audioArray,
      shuffleAudio,
      audio,
      handleAudio,
      letters,
      letterArray,
      shuffleLetter,
      handleLetterArray,
      message,
      handleSelectOne,
      handleSelectTwo,
      handleSelectThree,
      handleSelectFour,
      handleSelectNone
    }
  }
}

I want help in adding an event listener

I’m a django developer not good at javascript. I have a django template i really want to use Javascript for. i tried reading online for help but i’m not understanding

I want to add an addEventlistener to this code below

<div class="box-element hidden" id="request-info">
        <button id="send-payment">Send request</button>

Also, I want it to display a response when submitted. Response like “Request sent”. Please I know about console.log, I don’t want it in console.log.

I know JS is really good at this.

Change Angular base href with ngx-translate

I have already implemented ngx-translate succesfully. Now, I want to change the base href of my Angular project, depending on the language I choose from my header menu.

Currently, my URL looks like this: “localhost:4200”. Then, when you launch the project, it must show something like this: “localhost:4200/en” or like this: “localhost:4200/es”, depending on the choosen language.

My index html has this:

<base href="/"/>

And my header component ts file has a function that changes the language using ngx-translate. As you can see, I tried to use ‘replaceState’ to show the choosen language in the URL, and it worked, but it disappears once I navigate to another route.


import { Component, OnInit } from '@angular/core';
//For translate language
import { TranslateService } from '@ngx-translate/core'; 
import { Router, Event, NavigationStart, NavigationEnd } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {


  constructor(private translate: TranslateService,
              private router: Router,
              private location: Location,
              ) 
    { translate.addLangs(['es','en']);
      translate.setDefaultLang('es'); 
    }

  ngOnInit(): void {



  }


  useLanguage(language: string): void {
    this.translate.use(language); 
    // alert(language);

    // location.replace("https://www.google.com");
    // return;


    const modified_path = language;
    this.location.replaceState(modified_path);

  } 
 

}



Disabling jQuery animations for mobile only

I’m trying to disable the scrollTo animation in jQuery for mobile only. I have looked on Stackoverflow and none of the solutions have worked for me thusfar. Some of them point to this link but it didn’t help me.

I have the following code which is used to detect whether or not the user is on a mobile device but I’m not sure how to proceed after that. It’s likely staring at me in the face and I just don’t see it. I tried simply writing an if else statement within my function(gotodiv) but it didn’t work.


 (function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bbd+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Here is my jQuery if it helps:

$(document).ready(function(gotodiv) {
    function gotodiv(){
            $('html, body').animate({
                scrollTop: $("#divscr").offset().top
            }, 6000); 

    }

    window.setTimeout( gotodiv, 45000 ); //Time in milliseconds
   
});

error Command failed with exit code 134 web3 dapp react website

i’m a starter on reactjs / web3 / dapp coding, i started for one of my project and i got and issue that i can’t resolve it, i’m trying to make a website for mint some nft, i added react-helmet for try to add a title to my website and since that i got many error, i resolve some of them but now i got that and i dont know how i can resolve it

Command failed with exit code 134: npm run generate i tried this and it didn’t work !

<--- Last few GCs --->

[14260:000002D98912B060]   106202 ms: Mark-sweep 1965.7 (2094.4) -> 1965.7 (2094.4) MB, 1661.6 / 0.0 ms  (average mu = 0.115, current mu = 0.008) allocation failure scavenge might not succeed
[14260:000002D98912B060]   107977 ms: Mark-sweep 1966.8 (2095.6) -> 1966.8 (2095.6) MB, 1765.9 / 0.0 ms  (average mu = 0.063, current mu = 0.005) allocation failure scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF70241401F v8::internal::CodeObjectRegistry::~CodeObjectRegistry+112511
 2: 00007FF7023A3146 DSA_meth_get_flags+65542
 3: 00007FF7023A3FFD node::OnFatalError+301
 4: 00007FF702CD5ADE v8::Isolate::ReportExternalAllocationLimitReached+94
 5: 00007FF702CC000D v8::SharedArrayBuffer::Externalize+781
 6: 00007FF702B635FC v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1468
 7: 00007FF702B702A9 v8::internal::Heap::PublishPendingAllocations+1129
 8: 00007FF702B6D27A v8::internal::Heap::PageFlagsAreConsistent+2842
 9: 00007FF702B5FEF9 v8::internal::Heap::CollectGarbage+2137
10: 00007FF702B5E0B0 v8::internal::Heap::AllocateExternalBackingStore+2000
11: 00007FF702B7BD20 v8::internal::FreeListManyCached::Reset+1408
12: 00007FF702B7C3D5 v8::internal::Factory::AllocateRaw+37
13: 00007FF702B8E0CE v8::internal::FactoryBase<v8::internal::Factory>::AllocateRawArray+46
14: 00007FF702B90D2A v8::internal::FactoryBase<v8::internal::Factory>::NewFixedArrayWithFiller+74
15: 00007FF702B90F83 v8::internal::FactoryBase<v8::internal::Factory>::NewFixedArrayWithMap+35
16: 00007FF702999E5E v8::internal::HashTable<v8::internal::NumberDictionary,v8::internal::NumberDictionaryShape>::New<v8::internal::Isolate>+110
17: 00007FF702C8EFA0 v8::internal::Builtins::code_handle+167152
18: 00007FF702C8AEDD v8::internal::Builtins::code_handle+150573
19: 00007FF702C8A9C0 v8::internal::Builtins::code_handle+149264
20: 00007FF702D635B1 v8::internal::SetupIsolateDelegate::SetupHeap+494673
21: 000002D98B888789
error Command failed with exit code 134.

That’s my index.js :

import { useWeb3React } from "@web3-react/core"
import { injected } from "../components/wallet/connectors"
import 'bootstrap/dist/css/bootstrap.css'
import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
            </Helmet>
            ...
        </div>
    );
  }
};


export default function Home() {

  const { active, account, library, connector, activate, deactivate } = useWeb3React()
  
  async function connect() {
    try {
      await activate(injected)
    } catch (ex) {
      console.log(ex)
    }
  }

  async function disconnect() {
    try {
      deactivate()
    } catch (ex) {
      console.log(ex)
    }
  }
  
  return (
    <div className="container-fluid"> 
      <div className="row">
        <div className="col">
          
        </div>
        <div className="col-6">
          <h1 className="text-center title">ANGRY SHARKS</h1>
        </div>
        <div className="col text-end">
          {active ? <button onClick={disconnect} className="btn btn-outline-light connextion">Disconnect</button> : 
            <button onClick={connect} className="btn btn-outline-light connextion">Connect to metamask</button>}
        </div>
        <div className="container-fluid square-box d-flex justify-content-center align-items-center">
          <button type="button" className="btn btn-outline-light btn-lg" data-bs-toggle="button">MINT</button>
        </div>
      </div>
    </div>
  )
}

thanks for people who will help me i’m not very good in reactjs and web3 dapp coding

Place download request in one tab but complete in another

A web app opens new tab and places a POST request to the server to create a file for a download. Here is the code that sends the file back:

Response.AppendHeader("content-disposition", "attachment; filename=name");
Response.ContentType = "application/octet-stream";
Response.WriteFile(zipPath);
Response.Flush();
Response.End();

What can happen is that the user can close the new tab and no download would take a place. Is there any chance that the app would still get the file? I understand that placing request in the app is the way to go, but I am dealing with existing architecture.

Thanks for help.

Input value not changing on keypress and keyup events

import { useState } from "react";

export default function App() {
  const [height, setHeight] = useState('')

  const handleKeyPressUp = event => {
    const { value } = event.target

    setHeight(value)
  }

  return (
    <input
      value={height}
      onKeyPress={handleKeyPressUp}
      onKeyUp={handleKeyPressUp}
    />
  );
}

I’ve asked to use keypress instead of onChange to listen the input change. And I use both onKeyPress and onKeyUp because of onKeyPress is triggering right before the input value is changing(How to get text of an input text box during onKeyPress?), and also keypress will only be triggered for keys that produce a character value. i.e it won’t be triggered on back space(https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event).

But when assigning the state height value to the input value, the input won’t accept any input. Why the input value is not updated on typing text on the field?

Why does drawImage’s scaling add borders?

I’m not so sure if “borders” is the right term, but anyway:
My problem is that if I try to (up)scale a tile from a tile atlas, it adds parts of the tiles next to it.

My tile drawing code is as follows:

ctx.drawImage(tileAtlas, s.x, s.y, s.w, s.h, d.x, d.y, d.w, d.h);

s is the source and d the destination. The calculation for the destination’s width and height is the source’s multiplied by the scalar.

const d = {
            ...
            w: s.w *scalarX,
            h: s.h *scalarY
}

The end result for scaling by two look like this:

canvas scaled by two

The tileset:

the tileset

The lines appear for every tile that is (up)scaled and for every upscaling I tried (1.25, 1.5, 2, 5, 10, …) only 1, 0.75, 0.625, 0.5, 0.375, 0.25 and so on worked.

The size of the tiles is not the problem, here these are 64×64.
I also checked if the wrong positions have been given to s or d but they align to the upscaled tilesize of 128×128 that the destination shall have.

Here as a snipped, I scaled down the code as much as possible.

const canvasElement = document.getElementById("canvas");
const ctx = canvasElement.getContext("2d");

const tileAtlas = new Image();
tileAtlas.src = "https://i.stack.imgur.com/PdcQg.png"; //path to the tile atlas file; here the img in the post

const tiles = {
    width_x: 64,
    height_y: 64,
    scalar: 1
}
const canv = {
    width_x: 4, //size in tiles
    height_y: 4
}

/* applies canv to the canvas and clears it */
function applyCanvas() {
    const sizeX = canv.width_x * tiles.width_x * tiles.scalar;
    const sizeY = canv.height_y * tiles.height_y * tiles.scalar;
    canvasElement.setAttribute("width", sizeX);
    canvasElement.setAttribute("height", sizeY);
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, sizeX, sizeY);
}

/* draws the tile in tile atlas at tx, ty
 * to the canvas at cx, cy
 * the canvas cordinates are based on the tilesize
 */
function drawTile(tx=0, ty=0, cx=0, cy=0) {
    const s = {
        x: tx *tiles.width_x,
        y: ty *tiles.height_y,
        w: tiles.width_x,
        h: tiles.height_y
    };
    const d = {
        x: cx *s.w *tiles.scalar,
        y: cy *s.h *tiles.scalar,
        w: s.w *tiles.scalar,
        h: s.h *tiles.scalar
    };
    ctx.drawImage(tileAtlas, s.x, s.y, s.w, s.h, d.x, d.y, d.w, d.h);
}

/* draws the canvas full of the tile at tx, ty
 * and changes the scaling
 */
function fillWithScaler(tx=0, ty=0, scalar=1) {
    tiles.scalar = scalar;
    applyCanvas();
    for (var y = 0; y < canv.height_y; y++) {
        for (var x = 0; x < canv.width_x; x++) {
            drawTile(tx, ty, x, y);
        }
    }
}
<!DOCTYPE html>
<html>
    <body>
        Scaler: <input type="number" value="1" min="0" onchange="fillWithScaler(0, 3, this.value)"> <br>
        <canvas id="canvas" width="256" height="256" style="border: 1px solid gray;"></canvas>
    </body>
    <script src='test.js'></script>
</html>

How can i add a customization/Set Up page to a JS website

I want to add a page where users of my template can easily change the name of the website, logo etc to their taste by new typing the name into a text box or uploading it.

I want the website to be easily customized like wordpress.

I am doing this by adding the external scripts for customization to the various pages, but its not working. The html pages are no responding to the scripts. I am getting error = Uncaught TypeError: Cannot set properties of null (setting ‘src’).

I will appreciate every feed back. Thank you.

Search still works after deleting a user + cells keep being created without an input

been working on some basic contacts app and got stuck in two places. Cells keep being created in the table even if there’s no input (I’ve tried if statements) + after deleting a contact I can still search for it. How to remove it from the database? Is it possible to make the create button appear after all the fields have input in it? How can I remove the elements from db array after deleting the cells?

let db = [];
let contact = {};
// ADD CONTACT
$(document).ready(function() {
$("#create-contact").on("click", function(event) {
  event.preventDefault();

  contact.firstName = $('#name').val();
  contact.surname = $('#surname').val();
  contact.phone = $("#phone").val();
  contact.address = $("#address").val();

  let row = document.createElement("tr");
  $("table").append(row);
  let cell1 = document.createElement("td");
  let cell2 = document.createElement("td");
  let cell3 = document.createElement("td");
  let cell4 = document.createElement("td");
  let dltBtn = document.createElement("button");
  /* ^ https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
     Fastest method */

  $(dltBtn).text("X")
  .css("width", "8.5rem")
  .css("color", "white")
  .css("background-color", "black")
  .attr("class", "dltBtn");


  $(cell1).html(contact.firstName);
  $(cell2).html(contact.surname);
  $(cell3).html(contact.phone);
  $(cell4).html(contact.address);

  row.append(cell1, cell2, cell3, cell4,dltBtn);


  db.push(contact.firstName, contact.surname, contact.phone, contact.address);

  console.log(db);

  $('.dltBtn').on('click', function(event) {
      event.preventDefault();

    row.remove(dltBtn)
    .deleteCell();

  });

});

// SEARCH
function search(name) {
  for (i = 0; i < db.length; i++) {
    if (!isNaN(name) && db[i] === name) {
      return db[i-2] + "  " + db[i-1] + "   " + db[i] + "  " + db[i+1];
    }
    if (db[i].toUpperCase() === name.toUpperCase()) {
      return db[i] + "  " + db[i+1] + "   " + db[i+2] + "  " + db[i+3];
    }
    $("#found").text("User not found!");
  }


};

$('.searchbutton').on('click', function(event) {
    event.preventDefault();

    var findUserName = $('#query').val();
    var userFound = search(findUserName);

    $("#found").text(userFound);
    console.log(db);
});
});
```  ^ JS

Uncaught TypeError: window.Thing is not a function

I have a typescript module that creates a new object called Thing as so…

(function (window, factory: Function) {
  (window as any).Thing = factory(window)
})(window, function(window: Window){

  const Constructor = function(options?: {}){
    let publicAPIs: Object = {};

    publicAPIs.sayHello = function(){
      console.log("Hello")
    }

    return publicAPIs;

  }


  return Constructor;

});

But then when I call it in HTML, it’s getting giving an error Uncaught TypeError: window.Thing is not a function

<script>
    var myThing = window.Thing();
    myThing.sayHello()
</script>

If I’m in the console, I can run window.Thing() and window.Thing().sayHello() absolutely fine – so why isn’t it working normally?