JavaScript DOM Manipulation not working (Nothing Appears on Page)

I’m working on a project with a Webpack where I am trying to dynamically generate the content of a page using JavaScript. However, when I load the page, the content does not appear. Only the navigation bar is visible, and I can’t see any content being added to the #content div.

Here’s a breakdown of what I’ve tried:

/project-folder
  /dist
  /node_modules
  /src
    /index.js
    /greeting.js
    /template.html
  .gitignore
  package.json
  webpack.config.js

index.js

import { generatePage } from "./greeting";

generatePage()

greeting.js

export function generatePage(){
    
    const header=document.createElement("h1")
    const image=document.createElement("img")
    const headertwo=document.createElement("h2")
    const paragraph=document.createElement("p")
    header.textContent = "Welcome to Our Restaurant!";
    headertwo.textContent = "Best Dishes Served Fresh!";
    paragraph.textContent = "Our restaurant offers a variety of delicious meals made with love and care.";

    const container=document.querySelector("#content")

    container.appendChild(header)
    container.appendChild(image)
    container.appendChild(headertwo)
    container.appendChild(paragraph)
}

template.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Restaurant Page</title>

  </head>
  <body>
   <header>
    <nav>
        <button type="button">Home</button>
        <button type="button">Menu</button>
        <button type="button">About</button>
    </nav>
   </header>
   <div id="content">
    

   </div>

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
  },
  devtool: "eval-source-map",
  devServer: {
    watchFiles: ["./src/template.html"],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/template.html",
    }),
  ],
  module: {
    rules: [
      {
        test: /.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /.html$/i,
        loader: "html-loader",
      }
      
    ],
  },
};



What I’ve Tried:

  • I’ve added console.log statements in index.js and greeting.js to confirm that the scripts are running, but I don’t see any logs in the browser console.

  • I made sure the Webpack development server is running and the page is reloading correctly (npx webpack serve).

  • The page loads, but only the navigation bar is visible, and none of the content (like the header, image, and paragraph) is being added to the #content div.

What I Expect:

I expect the content to be dynamically generated and added to the #content div after the page loads, but it’s not appearing. The log messages also don’t show up in the console.

What is the process for making a signal “Stable” so that it can be emitted by an Observable created with toObservable()?

In the RxJS Interop documentation for Angular 19 it says:

Unlike Observables, signals never provide a synchronous notification of changes. Even if you update a signal’s value multiple times, toObservable will only emit the value after the signal stabilizes.

And it gives this example:

const obs$ = toObservable(mySignal);
obs$.subscribe(value => console.log(value));
mySignal.set(1);
mySignal.set(2);
mySignal.set(3);

In the above case only 3 gets logged.

So how do we “Stabilize” my signal after if we want each set call to be emitted by the corresponding observable?

Is it enough to always wrap the set in a method call like this and are there any other ways of doing it?

updateMySignal(value: number) {
   this.mySignal.set(value);
}

How to get a Thymeleaf fragment from a Spring ResponseEntity with ajax.post()

First question here (which means I’m really stucked :’D) !

I want to implement the suppression of several objectfs, and handle in my controller the different errors that might happen. I call the controller with ajax, and want to load up a fragment in my html that will indicates what happened.

I don’t understand what makes ajax get my thymeleaf fragment when he receives a string in response.

Controller :

@PostMapping("/deleteMultipleMyObjects")
@ResponseBody
public ResponseEntity<Object> deleteMultipleMyObjects(Model model, @ModelAttribute("myObjectIds") String myObjectIds) {

        if (myObjectIds.length() == 0) {
            MessageHelper.addInfoAttribute(model, "objects.delete.none");
            return ResponseEntity.badRequest().body("fragments/components :: ajaxResponse");
        }

        // The service brings back two lists : the ids deleted and those non-deleted (for any reason)
        Pair<List<Long>, List<Long>> res = myObjectService.deleteMultipleMyObjects(myObjectIds);

        if (!res.getValue1().isEmpty()) {
            // Here I want to send back a warning, and handle the objects I did not delete
            MessageHelper.addWarningAttribute(model, "objects.delete.warn", res.getValue1());
            return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).body(new Pair<>(res.getValue0(), "fragments/components :: ajaxResponse"));
        }
        // If all goes well, success
        MessageHelper.addSuccessAttribute(model, "objects.delete.ok");
        return ResponseEntity.accepted().body("fragments/components :: ajaxResponse");
    }

The fragment I want to get (and that is used many times in my code) – components.html :

<div id="ajaxResponse" th:fragment="ajaxResponse (type, message)" class="alert alert-dismissable" th:classappend="'alert-' + ${message.type.name().toLowerCase()}">
  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
  <span th:if="${message.args==null or message.args.length==0}" th:text="#{${message.message}}">An error happened</span>
  <span th:if="${message.args!=null and message.args.length==1}" th:text="#{${message.message}(${message.args[0]})}">An error happened</span>
</div>

The html where I visualize and handle my objects – objects.html :

<div id="alertDiv">
</div>
<div id="deleteMultipleMyObjects" class="btn" onclick="deleteMultipleMyObjects()">Delete multiple objects</div>
  <table>
  <!-- a table containing my objects and with a checkbox to select those who will be deleted-->
  </table>

And finally my javascript – objects.js :

function deleteMultipleMyObjects() {
  let myObjectIds = getAllCheckedObjects(); // sends back a string with the ids of the checked objects : "id1,id3,id6"

  let fragment;
  $.post("deleteMultipleMyObjects", {myObjectIds: myObjectIds})
  .done(function (data, status, xhr){
    hideAllCheckedObjects();
    fragment = data; // !!! Here I get the name of the fragment instead of the html
  })
  .fail(function(xhr, status, error){
    if (undefined != xhr.responseJSON && xhr.responseJSON.value0.length > 0) {
      hideLinesWithId(xhr.responseJSON.value0);
      fragment = xhr.responseJSON.value1; // !!! Here I get the name of the fragment instead of the html
    } else {
      fragment = xhr.responseText; // !!! Here I get the name of the fragment instead of the html
    }
  })
  .always(function(xhr, status, error) {
    $("#alertDiv").text("");
    $("#alertDiv").append(fragment); // !!! Here I'd like my alertDiv to receive the full html of my fragment
  });
}

Each time I get an xhr or data containing literally the name of the fragment (“fragments/components :: ajaxResponse”) instead of the html of it.
I got other places in my code where I use $.ajax or $.post and I get back the html of the fragment but at those places my Controller sends back a String and not a ResponseEntity. Here I’d really like to have my http response code to handle the different responses and also a body with data and also my fragment. It seems I can’t have them all…

How can I resolve the console warning “Google Maps JavaScript API has been loaded directly without loading=async.”?

I’m trying to load the Google Maps JavaScript API in a Blazor application. However, the console keeps showing the warning:

Google Maps JavaScript API has been loaded directly without loading=async.
This can result in suboptimal performance.
For best-practice loading patterns please see https://goo.gle/js-api-loading

I am using async defer (and have also tried loading=”lazy”) in my tag in App.razor, but the warning persists.

<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places" loading="async" async defer></script>

I have a Blazor interop function that looks like this:

async function window.initializeGoogleMapsAutocomplete = (autocompleteElement, dotNetRef) => {
    // Restricting the autocomplete to place type '(cities)' helps
    // to limit suggestions to geographic locations rather than addresses.
    const autocomplete = new google.maps.places.Autocomplete(autocompleteElement, {
        types: ['(cities)']
    });

    autocomplete.addListener('place_changed', function () {
        const place = autocomplete.getPlace();
        let city = "";
        let state = "";

        if (place.address_components) {
            for (const component of place.address_components) {
                const types = component.types;

                // "locality" usually indicates city
                if (types.indexOf("locality") !== -1) {
                    city = component.long_name;
                }
                // "administrative_area_level_1" usually indicates state (short name, e.g. "CA")
                if (types.indexOf("administrative_area_level_1") !== -1) {
                    state = component.short_name;
                }
            }
        }

        // Call Blazor method to set city & state on the .NET side
        dotNetRef.invokeMethodAsync("SetCityState", city, state);
    });
};

It just runs after the Maps script is loaded, so I don’t think it’s related to the warning. But I’m including it just in case.

How can I make this warning in the console go away?

Google Apps Script for inserting data onformsubmit is executing, but not inserting any data

I’m trying to reactivate scripts in Google Sheets which broke when my colleague’s account got deactivated. He created them. They functioned before he left.

Now, these only work when I manually submit data to the spreadsheet, which gets fed data from a Google Form. But the scripts do not function correctly when the form submits the data.

Here is one example:

function updateColumnsBasedOnCondition() {
    // Replace 'YOUR_SHEET_ID' and 'SHEET_NAME' with your actual sheet ID and sheet name
    var sheet = SpreadsheetApp.openById('1Ew25yFrtVlejqGgO6LKpZFe4sjO3hQ4fdGHg7Xbcaag').getSheetByName('New 2024 QD+');

if (!sheet) {
    Logger.log("Sheet not found");
    return;
}

// Get the data range of the sheet
var range = sheet.getDataRange();

// Get all the values in the sheet as a 2D array
var values = range.getValues();

// Iterate through each row in the data
for (var i = 0; i < values.length; i++) {
    var cellOValue = values[i][14]; // Value in column O for the current row (assuming index 14 for column O)
    var cellPValue = values[i][15]; // Value in column P for the current row (assuming index 15 for column P)

    // Log the value of column O
    Logger.log('Row ' + (i + 1) + ' Column O value: ' + cellOValue);

    // Check if column O value equals 'Standard new DC order'
    if (cellOValue.toString().trim() === 'Standard new DC order') {
        // Log that the condition was met
        Logger.log('Condition met at row ' + (i + 1));

        // Update corresponding columns Q, R, S, V, W, X, Z (assuming indexes 16, 17, 18, 21, 22, 23, 26)
        sheet.getRange(i + 1, 17).setValue(250); // Column Q (index 16 + 1)

        if (cellPValue.toString().trim() === 'Pending State Petitions') {
            sheet.getRange(i + 1, 18).setValue(30); // Column R (index 17 + 1)
            sheet.getRange(i + 1, 19).setValue('Double-sided'); // Column S (index 18 + 1)
        } else if (cellPValue.toString().trim() === 'Passed States Petitions') {
            sheet.getRange(i + 1, 20).setValue(30); // Column T (index 19 + 1)
            sheet.getRange(i + 1, 21).setValue('Double-sided'); // Column U (index 20 + 1)
        }

        sheet.getRange(i + 1, 22).setValue(50); // Column V (index 21 + 1)
        sheet.getRange(i + 1, 23).setValue(25); // Column W (index 22 + 1)
        sheet.getRange(i + 1, 24).setValue(25); // Column X (index 23 + 1)
        sheet.getRange(i + 1, 26).setValue(25); // Column Z (index 25 + 1)

        // Log that the values were set
        Logger.log('Values set for row ' + (i + 1));
    }
}

// Flush the logs
Logger.log('Script completed.');
}

Troubleshooting steps:

  1. I copy/pasted all his original scripts back in after deleting.
  2. I tried each of them one at a time.
  3. I tried revising each from ground zero.
  4. I fixed triggers under the “trigger” section
  5. I tried various triggers: onedit, onformsubmit, updatecolumnbasedonconditions
  6. Sometimes the execution log reads “failed” and sometimes it reads “complete,” but the result is always the same. Data is not placed.

Binance tr api ,binance websocket sometimes not sending data

I use binance tr api for my trading bot ;
Some days my bot works perfectly and i get all data via websocket.
Some days ( or sometimes ) bot cannot receive data.

I use Nodejs on window 11.

const wsgonder={"method":"SUBSCRIBE","params":["!miniTicker@arr@3000ms"]};

    var alinacak={};
const ws = new WebSocket("wss://stream-cloud.binance.tr/stream");
ws.on('open', function open() {


  ws.send(JSON.stringify(wsgonder));
});

ws.on("ping",(e)=>{
    console.log(e.toString());
    ws.pong();
})
var count=0;
ws.on("message", async function incoming(data) {
    
count++;
console.log(count)

})

For example : sometimes count stop at 20 , sometimes stop at 10…..
Sometimes works perfectly all day long.

What does “Cannot Read Properties of Undefined” mean in JavaScript? [closed]

I was writing with Javascript, and it was throwing the error, “Cannot read properties of undefined” (reading ‘title’)

var movies = [
  { 
      title: "Puff the Magic Dragon",
      review: "Best movie ever!!"
  },
  {
      title1: "fhf",
      review1: "dfd"
  }
];
for(var i=0;i<3;i++)
  {
  fill(84, 140, 209);
  textAlign(CENTER, CENTER);
  textSize(20);
  text(movies[i].title, 200, 5);
  textSize(10);
  text(movie[i].review, 200, 80);
  }

I was expecting it to read Puff the Magic Dragon, then Best Movie Ever!!, then fhf, dfd,
but it threw the error

Cannot Read Properties of Undefined

Webcam footage stopping when mouseClicked to take an image of video

I’m learning about image processing in class and I need to be able to take a screenshot of the webcam video that I’m displaying to the screen currently using p5.js. The problem is when I click the mouse to take the image, the webcam video stops/freezes on the frame when I clicked the mouse to take the image. I’m not sure what the problem is/how to keep the webcam video live after I have taken the picture.
Thank you!

let video;
let img;

function setup()
{
  createCanvas(900,600);
  pixelDensity(1);
  video = createCapture(VIDEO);
  video.hide(); //hidden default video showing
}

function draw()
{
  background(255);

  imageMode(CENTER);
  translate(width/2, height/2);
  scale(-1,1,1); //flip image to be correct orienation 
  image(video, 0,0, 160, 120);
}


function saveImage()
{
  img = video.get()
  save(img, 'myPic.png');
}

function mousePressed()
{
  saveImage();
}

Jest mock mockReturnValue not a function

Hi I am trying to mock a function from a module within my node_modules. The current way I have tried is

import { getPriceImpactForPosition } from "@gmx-io/sdk/utils/fees/priceImpact.js";
import { getBasisPoints } from "@gmx-io/sdk/utils/numbers.js";

// Move these mocks before any imports
jest.mock("@gmx-io/sdk/utils/fees/priceImpact.js", () => ({
  getPriceImpactForPosition: jest.fn()
}));

jest.mock("@gmx-io/sdk/utils/numbers.js", () => ({
  getBasisPoints: jest.fn()
}));

but when I call .mockReturnValue on the mock it says it is not a function. I assume that it is not being mocked properly, and is still calling the actual implementation.

Below is my jest.config.js file

/** @type {import('ts-jest').JestConfigWithTsJest} **/
export default {
  preset: "ts-jest/presets/js-with-ts-esm",
  testEnvironment: "node",
  testPathIgnorePatterns: ["/node_modules/", "/dist/"],
  transformIgnorePatterns: ["node_modules/(?!(@gmx-io/sdk))"],
  extensionsToTreatAsEsm: [".ts", ".jsx"],
  transform: {
    "^.+\.(ts|js|mjs)$": ["ts-jest", {
      useESM: true,
      tsconfig: "tsconfig.json",
    }],
  },
  moduleNameMapper: {
    "^(\.{1,2}/.*)\.js$": "$1"
  }
};

I had a look into the package as well to find the functions that I am trying to mock, it seems that the module itself is using package exports and I am not sure if this will affect mocking in anyway

  "exports": {
    ".": {
      "import": "./build/src/index.js",
      "require": "./build/src/index.js"
    },
    "./abis/*": "./build/abis/*",
    "./prebuilt/*": "./build/prebuilt/*",
    "./utils/*": "./build/src/utils/*",
    "./types/*": "./build/src/types/*",
    "./configs/*": "./build/src/configs/*"
  },

This is currently how I am running my tests

NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests

How to use Webpack with Google Maps APILoader for Address Autocomplete?

I am trying to integrate Google Maps’ Address Autocomplete feature using APILoader from the Extended Component Library.

The provided Google example uses direct ES module imports from a CDN:

import { APILoader } from 'https://ajax.googleapis.com/ajax/libs/@googlemaps/extended-component-library/0.6.11/index.min.js';

However, I want to integrate this properly into a Webpack-based project instead of relying on CDN imports.

My Current Code (CDN-based)

    import {APILoader} from 'https://ajax.googleapis.com/ajax/libs/@googlemaps/extended-component-library/0.6.11/index.min.js';

const CONFIGURATION = {
    "ctaTitle": "Checkout",
    "mapOptions": {"center":{"lat":37.4221,"lng":-122.0841},"fullscreenControl":true,"mapTypeControl":false,"streetViewControl":true,"zoom":11,"zoomControl":true,"maxZoom":22,"mapId":""},
    "mapsApiKey": "",
    "capabilities": {"addressAutocompleteControl":true,"mapDisplayControl":true,"ctaControl":true}
};

const SHORT_NAME_ADDRESS_COMPONENT_TYPES =
    new Set(['street_number', 'administrative_area_level_1', 'postal_code']);

const ADDRESS_COMPONENT_TYPES_IN_FORM = [
    'location',
    'locality',
    'administrative_area_level_1',
    'postal_code',
    'country',
];

function getFormInputElement(componentType) {
    return document.getElementById(`${componentType}-input`);
}

function fillInAddress(place) {
    function getComponentName(componentType) {
        for (const component of place.address_components || []) {
            if (component.types[0] === componentType) {
                return SHORT_NAME_ADDRESS_COMPONENT_TYPES.has(componentType) ?
                    component.short_name :
                    component.long_name;
            }
        }
        return '';
    }

    function getComponentText(componentType) {
        return (componentType === 'location') ?
            `${getComponentName('street_number')} ${getComponentName('route')}` :
            getComponentName(componentType);
    }

    for (const componentType of ADDRESS_COMPONENT_TYPES_IN_FORM) {
        getFormInputElement(componentType).value = getComponentText(componentType);
    }
}

function renderAddress(place) {
    const mapEl = document.querySelector('gmp-map');
    const markerEl = document.querySelector('gmp-advanced-marker');

    if (place.geometry && place.geometry.location) {
        mapEl.center = place.geometry.location;
        markerEl.position = place.geometry.location;
    } else {
        markerEl.position = null;
    }
}

async function initMap() {
    const {Autocomplete} = await APILoader.importLibrary('places');

    const mapOptions = CONFIGURATION.mapOptions;
    mapOptions.mapId = mapOptions.mapId || 'DEMO_MAP_ID';
    mapOptions.center = mapOptions.center || {lat: 37.4221, lng: -122.0841};

    await customElements.whenDefined('gmp-map');
    document.querySelector('gmp-map').innerMap.setOptions(mapOptions);
    const autocomplete = new Autocomplete(getFormInputElement('location'), {
        fields: ['address_components', 'geometry', 'name'],
        types: ['address'],
    });

    autocomplete.addListener('place_changed', () => {
        const place = autocomplete.getPlace();
        if (!place.geometry) {
            // User entered the name of a Place that was not suggested and
            // pressed the Enter key, or the Place Details request failed.
            window.alert(`No details available for input: '${place.name}'`);
            return;
        }
        renderAddress(place);
        fillInAddress(place);
    });
}

initMap();

My webpack conf :

    const Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or subdirectory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('app', './assets/app.js')
    .addEntry('register', './assets/register.js')
    .addEntry('address-selection', './assets/address_selection.js')

    .copyFiles({
        from: './assets/images',
        to: 'images/[path][name].[ext]',
        pattern: /.(png|jpg|jpeg|svg|gif|webp|ico)$/
    })

    .copyFiles({
        from: './assets/icons',
        to: 'icons/[path][name].[ext]',
        pattern: /.(png|ico)$/
    })

    .copyFiles({
        from: './assets',
        to: 'site.webmanifest',
        pattern: /site.webmanifest$/
    })

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // configure Babel
    // .configureBabel((config) => {
    //     config.plugins.push('@babel/a-babel-plugin');
    // })

    // enables and configure @babel/preset-env polyfills
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = '3.38';
    })

    // enables Sass/SCSS support
    .enableSassLoader()

    //.addExternals()

// uncomment if you use TypeScript
//.enableTypeScriptLoader()

// uncomment if you use React
//.enableReactPreset()

// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())

// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

How do I correctly configure Webpack to use APILoader? Do I need to install a package via npm, or is there an alternative approach? Also, how do I handle the importLibrary calls within Webpack?

Any guidance or example configurations would be greatly appreciated!

AG Grid SSRM Datasource client in JS is not working. Getting `TypeError: params.successCallback is not a function` error

I’m trying to attach as SSRM Data source for AG Grid table. I followed the official tutorial for that. https://www.ag-grid.com/javascript-data-grid/server-side-operations-nodejs. It’s using ag-grid npm package.

I’m trying to do the same with using Vanila js. (Without using npm packages). This will be a template to be rendered with Django. That’s why I’m staying away from npm packages in this case.

Followng is my index.html file. I’m using the same backend for this to get connected to.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

    <!-- ag-grid -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ag-grid-enterprise.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            agGrid.LicenseManager.setLicenseKey("Lisence key");
        })
    </script>
</head>
<body class="bg-light">
<!-- Main Content -->
<main class="col-md-10 col-lg-10 px-md-4 pt-4 bg-white">
    <div class="container-fluid">
        <div id="modules" class="ag-theme-alpine" style="height: 60vh; width: 100%;"></div>
    </div>
</main>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const gridOptions = {

            rowModelType: 'serverSide',

            columnDefs: [
                {field: 'athlete'},
                {field: 'country', rowGroup: true, hide: true},
                {field: 'sport', rowGroup: true, hide: true},
                {field: 'year', filter: 'number', filterParams: {newRowsAction: 'keep'}},
                {field: 'gold', aggFunc: 'sum'},
                {field: 'silver', aggFunc: 'sum'},
                {field: 'bronze', aggFunc: 'sum'},
            ],

            defaultColDef: {
                sortable: true
            }

            // debug: true,
            // cacheBlockSize: 20,
            // maxBlocksInCache: 3,
            // purgeClosedRowNodes: true,
            // maxConcurrentDatasourceRequests: 2,
            // blockLoadDebounceMillis: 1000
        };

        const gridDiv = document.querySelector('#modules');
        const api = agGrid.createGrid(gridDiv, gridOptions);

        const datasource = {
            getRows(params) {
                console.log(JSON.stringify(params.request, null, 1));

                fetch('http://localhost:4000/olympicWinners/', {
                    method: 'post',
                    body: JSON.stringify(params.request),
                    headers: {"Content-Type": "application/json; charset=utf-8"}
                })
                    .then(httpResponse => httpResponse.json())
                    .then(response => {
                        params.successCallback(response.rows, response.lastRow);
                    })
                    .catch(error => {
                        console.error(error);
                        params.failCallback();
                    })
            }
        };

        api.setGridOption('serverSideDatasource', datasource);
    })
</script>
</body>
</html>

This is fetching the data from back-end and not displaying in table. When I checked the console I found following errors.

TypeError: params.successCallback is not a function
Uncaught (in promise) TypeError: params.failCallback is not a function

I think the way I defined the data source in front end is not correct. Searched for hours and didn’t get any solution.

PS: I have allowed CORS in browser to fetch the data from backend and data is getting logged as expected.

Convert Array of primitives to ArrayBuffer

I am trying to use Web Workers, and I noticed that to improve performance you can use “transferable” objects in postMessage

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

In Deno, transferable object means ArrayBuffer, but how to transform an array variable to ArrayBuffer ?

my use case is sending array of around 10k elements to the web worker, so I’d like to not copy it if possible.

Triangle, Circle, Square – SVG morphing on scroll

enter image description here

Trying to recreate this javascript scrolling animation – responding to changes in scroll direction and morphing between different transitions

I want to replicate this in gsap — this version shows the morph from triangle to circle — but then needs to morph to rectangle to flatten the sides out

https://codepen.io/theoldcounty/pen/VYwYwGQ

// gsap.to()... infinity and beyond!
// To learn how to use GSAP, go to greensock.com/get-started

gsap.registerPlugin(ScrollTrigger);

var tl = gsap.timeline();
hippo = document.getElementById("hippo");

tl.to(
  hippo,
  {
    morphSVG: "#circle",
    duration: 1,
    scrollTrigger: {
      trigger: "#v-spacer-1",
      markers: false,
      scrub: true,
      start: "top top"
    }
  },
  "+=1"
);
@import url("https://fonts.googleapis.com/css?family=Signika+Negative:300,400&display=swap");
* {
  box-sizing: border-box;
}

body {
  font-family: "Signika Negative", sans-serif;
  font-weight: 300;
  margin: 0;
}
.v-spacer {
  height: 90vh;
  width: 100%;
  scroll-snap-align: center;
}

svg {
  display: block;
  width: 100vw;
  height: 100vh;
}

path {
  fill: linear-gradient(to right, #ff0000, #00ff00);
}

#svg2 {
  position: fixed;
}

#circle {
  visibility: hidden;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>CodePen - Gsap Scroll Morphing</title>
  <link rel="stylesheet" href="./style.css">

</head>

<body>
  <!-- partial:index.partial.html -->
  <svg version="1.1" id="svg2" inkscape:version="0.91 r13725" sodipodi:docname="Domestic_Dromedary_silhouette.svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" style="enable-background:new 9 80 800 400;" xml:space="preserve">
    <style type="text/css">
      .st1 {
        fill: black;
      }
    </style>

    <!--SHAPE #1-->
    <path id="circle" class="st1" d="M 0 0 A 1 1 0 0 0 1000 0" />

    <!--SHAPE #2-->
    <path id="hippo" class="st1" d="M 0 0 L 500 500 L 1000 0" />

    <div id="v-spacer-1" class="v-spacer">

    </div>
    <div id="v-spacer-2" class="v-spacer">

    </div>
    <!-- partial -->
    <script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/CSSRulePlugin.min.js'></script>
    <script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/MorphSVGPlugin3.min.js'></script>
    <script src='https://unpkg.com/gsap@3/dist/ScrollTrigger.min.js'></script>
    <script src="./script.js"></script>

</body>

</html>

HTML & CSS with JavaScript Problem on CodePen with screen refresh when animating border property through slider control

I am a teacher who has made an interactive HTML and CSS Box Model explainer for students to help them understand how it works. I am having issues understanding why the screen won’t update smoothly when adjusting the control slider for the padding property.

https://codepen.io/Mr-Werrey-Easterbrook/pen/wBvvVKw?editors=0011

 padding_slider.oninput = function() {
   console.log(this.value);
   picture.style.padding=this.value +"px";
 }

Axios $type property not being deserialized correctly

I have a vue.js project that communicates with a .Net backend via rest calls.
The part that is of interest contains 2 JSON objects with a property called $type, property which is generated by the backed because there is an array that can contain multiple types of objects.

the line of code that deserializes:

const response = await new Http().apiServer().get(this.endpoint);

the implementation of the apiServer() method:

public apiServer(): AxiosInstance {
    return axios.create({
        baseURL: this.configuration.API_URL,
    });
}

1st json api response:

{
    "content": {
        "elementsList": [
            {
                "index": 1,
                "segments": [
                    {
                        "$type": "typeb",
                        "someBooleanValue": false,
                        "someOtherChildComponents": [
                            {
                                "index": 1,
                                "text": "dfasdfasdfsadfsdf",
                                "anotherArray": [
                                    {
                                        "index": 1,
                                        "text": "maybe"
                                    },
                                    {
                                        "index": 2,
                                        "text": "no"
                                    }
                                ]
                            }
                        ],
                        "index": 1,
                        "title": "dummy title nb 1"
                    },
                    {
                        "$type": "typeb",
                        "someBooleanValue": true,
                        "someOtherChildComponents": [
                            {
                                "index": 1,
                                "text": "sfsdfasfsfsfsf",
                                "anotherArray": [
                                    {
                                        "index": 1,
                                        "text": "fsafasdfsafsdf"
                                    },
                                    {
                                        "index": 2,
                                        "text": "sadfsadfsadfsadfsadfsadfdsa"
                                    },
                                    {
                                        "index": 3,
                                        "text": "sadfsadfasdfdsaf"
                                    }
                                ]
                            },
                            {
                                "index": 2,
                                "text": "dafdsafasfsdffdfafsffadfadfasdf",
                                "anotherArray": [
                                    {
                                        "index": 1,
                                        "text": "safsafsadfsaffsa"
                                    },
                                    {
                                        "index": 2,
                                        "text": "sadfsafsadfafsad"
                                    },
                                    {
                                        "index": 3,
                                        "text": "dfasdfsadfasd"
                                    }
                                ]
                            },
                            {
                                "index": 3,
                                "text": "dfsadfsadfsadfsadf",
                                "anotherArray": [
                                    {
                                        "index": 1,
                                        "text": "sadfsadfsadfa"
                                    },
                                    {
                                        "index": 2,
                                        "text": "fasfdsadfsadfad"
                                    },
                                    {
                                        "index": 3,
                                        "text": "sadfasdfasfsadf"
                                    },
                                    {
                                        "index": 4,
                                        "text": "fsdfsdfaasdfasfadf"
                                    }
                                ]
                            }
                        ],
                        "index": 2,
                        "title": "dummy title nb 2"
                    },
                    {
                        "$type": "typea",
                        "htmlContent": <p>dummy</p>",
                        "index": 3,
                        "title": "dummy title nb 3"
                    }
                ]
            }
        ]
    },
    "status": 0,
    "otherValue": 0
}

2nd json api response is the “content” of the first one.

the type i am trying to map to:


export type payloadType = {
    content: ContentType;
    statusType: TStatus;
    otherValue: number;
};

export enum SegmentType {
    TypeA = 'typea',
    TypeB = 'typeb',
}

export interface Segment {
    $type: SegmentType;
    index: number;
    title: string;
}

export interface TypeASegment extends Segment {
    $type: SegmentType.TypeA;
    htmlContent: string;
};

export interface TypeBSegment extends Segment{
    $type: SegmentType.TypeB
    someBooleanValue: boolean;
    someOtherChildComponents: OtherChildComponentType[];
};

The issue is when i log the response of the get request:

  1. when i call the endpoint that returns the 1st json response all of the $type attributes are “typea”.
  2. when i call the endpoint that returns the 2nd json response the $type attributes are being mapped correctly, first 2 being typeb and the last one typea

I played around a bit with the segment type values and what seems to happed is that all the types are mapped to what is the value that i use in TypeASegment

I also noticed that the types are still impacting the mapping even though i am not doing any typecasting or declaring the type that i want the.