D3.js Getting event object instead of data after adding ‘onchange’ event to listitem

I used the code showed by this video (see from 24:34 time)

https://www.youtube.com/watch?v=aHJCt2adSWA

to make an interactive bar chart with D3.js Version 7

the video was made in 2020 and used version 5

the strange issue I am facing is that I am getting , when calling console.log(data) in the code below, the event object:

Event {isTrusted: true, type: ‘change’, target: input, currentTarget:
input, eventPhase: 2, …}isTrusted: truebubbles: truecancelBubble:
falsecancelable: falsecomposed: falsecurrentTarget:
nulldefaultPrevented: falseeventPhase: 0path: (9) [input, li, ul,
div#data, div#app, body, html, document, Window]returnValue:
truesrcElement: inputtarget: inputtimeStamp: 239761.39999997616type:
“change”[[Prototype]]: Event D3JSCHART-interactive1.html:131

instead of the data Array (as the presenter is getting in his video)

enter image description here

const listItems=d3
.select('#data')
.select('ul')
.selectAll('li')
.data(MyData)
.enter()
.append('li');
listItems.append('span').text(data => data.region);
listItems.append('input').attr('type','checkbox').attr('checked',true)
.on('change',(data) => {
console.log(data);
});

below the full code

<html lang="fr">
<head>
<style>
#app{
display:flex;
margin:2rem 1rem;
}
#data ul
{
list-style:none;
margin:0;
padding:0
}
#data li
{
margin-bottom:1rem;
padding:1rem;
box-shadow:0 2px 8px rgba(0, 0, 0, 0.6);
width:10rem;
display:flex;
justify-content:space-between;
align-items:center;
font-weight:bold;
}
.label
{
background-color:green;
fill:#ff0077;
font-size:9px;
}

.bar {
fill:#ff0077;}
</style>
<title>D3.JS CHART Interactive 06/03/2022</title>
<!-- https://www.youtube.com/watch?v=aHJCt2adSWA-->
<script src="https://d3js.org/d3.v7.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/d3-scale@4" ></script>
<script src="https://cdn.jsdelivr.net/npm/d3-axis@3"></script>
</head>

<body>
<div id="app">
<div id="chart"><svg></svg></div>
<div id="data"><ul></ul></div>
</div>
<script>
const MyData=
[ 
{id:'d1',value:15, region:'Tunisia'},
{id:'d2',value:13, region:'Algeria'},
{id:'d3',value:17, region:'Egypt'},
{id:'d4',value:28, region:'Lybia'},
{id:'d5',value:19, region:'Sudan'}];

const MARGINS={top:20, bottom:15};
const CHART_Width=600;
const CHART_HEIGHT=400 -MARGINS.top-MARGINS.bottom;

let selectedData=MyData;

const x=d3
.scaleBand().rangeRound([0, CHART_Width]).padding(0.1);
const y=d3
.scaleLinear().range([CHART_HEIGHT, 0]);

const ChartContainer=d3.
select('svg')
.attr('width',CHART_Width)
.attr('height',CHART_HEIGHT +MARGINS.top+MARGINS.bottom);

x.domain(MyData.map(d => d.region));
y.domain([0, d3.max(MyData,d => d.value)+3]);



let unselectedIds=[];

const chart=ChartContainer.append('g');

chart
.append('g')
.call(d3.axisBottom(x).tickSizeOuter(0))
.attr('transform',`translate(0,${CHART_HEIGHT})`)
.attr('color','#4f009e');

function renderChart()
{
chart
.selectAll('.bar')
.data(selectedData, data => data.id)
.enter()
.append('rect')
.classed('bar',true)
.attr('width',x.bandwidth())
.attr('height',data => CHART_HEIGHT -y(data.value))
.attr('x',(data) => x(data.region))
.attr('y',(data) => y(data.value));

chart.selectAll('.bar').data(selectedData).exit().remove();

chart
.selectAll('.label')
.data(selectedData, data => data.id)
.enter()
.append('text')
.text((data) => data.value)
.attr('x',data => x(data.region)+x.bandwidth()/2)
.attr('y',data => y(data.value)-7)
.attr('text-anchor','middle')
.classed('label',true);

chart.selectAll('.label').data(selectedData).exit().remove();
}


renderChart();



const listItems=d3
.select('#data')
.select('ul')
.selectAll('li')
.data(MyData)
.enter()
.append('li');
listItems.append('span').text(data => data.region);
listItems.append('input').attr('type','checkbox').attr('checked',true)
.on('change',(data) => {
console.log(data);

/*if(unselectedIds.indexOf(data.id) === -1)
{unselectedIds.push(data.id);}
else
{unselectedIds=unselectedIds.filter(id => id !== data.id);}

SelectedData=MyData.filter(
(d) => unselectedIds.indexOf(d.id) === -1

);
renderChart();
*/
});



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

Eventlistener only works after clicking twice

My addEventListener only works when I click the image twice. The console log does say that the item has been deleted from the database, I see this as well in the array. This means that the function works, but why does it take two times to actually delete the item from the DOM?

const addToDom = async (data) => {
const item = document.createElement("li");
item.innerHTML = '';

data.forEach((task) => {
    const deleteImage = document.createElement('img');
    const toDoList = document.getElementById("todo-list");
    deleteImage.id = task._id;
        
    item.classList.add("task-item");
    deleteImage.src = 'bin.png';
    item.innerHTML = task.description;
    toDoList.appendChild(item); 
    item.appendChild(deleteImage);

    deleteImage.addEventListener("click", (event) => {

            const idToDelete = event.target.id;
            toDoList.removeChild(item);
            item.innerHTML = '';
            console.log(`Delete ${task.description}`);
            deleteData(idToDelete);
            loadData(data);
    });
    
});

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code.
test.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title
</head>

<body>
    <script type="module" src="./test.js"></script>
</body>

</html>

test.js

import * as tf from "./node_modules/@tensorflow/tfjs";
import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter";

const MODEL_URL = './model.json';

const model = await loadGraphModel(MODEL_URL);
const cat = document.getElementById('cat');
model.execute(tf.browser.fromPixels(cat));

Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Can anyone help to solve this? Thank you

Create a Javascript vidiprinter

I’m using javascript on a webpage and looking for a way to create a vidiprinter effect to output text to a text area on a web page. I mean in the style of how they use to do the latest football results back in the 80’s and with an ‘*’ as the flashing cursor.

For example it would first show * flashing for a couple of seconds and then start typing out the text one letter at a time with the * flashing as it goes along.

Hope that makes sense with what I’m after. I’ve tried myself using different methods but with no success.

Mongoose empty subdocument array

I made this mongoose schema with a nested array of subdocuments:

const deliverySchema = new db.Schema({
   price: Number
})

const suppliersSchema = new db.Schema({
    name: String,
    deliveries: [deliverySchema]
})

exports.Suppliers = db.model('Suppliers', suppliersSchema)
const suppliers = new Suppliers({name})

await suppliers.save()

But when I try to save a document i get this error:

TypeError: Cannot read properties of undefined (reading 'length')
    at cloneArray...

If I remove the subdocument from the schema the document gets saved without issues.

Why can’t I save the document with this schema?

Send data from java to JavaScript using WebView

i’m trying to make a map java project using web view , i want to send the Longitude and Latitude from java to JavaScript .

i have used the webengine.executeScript("latitude") like this

Java

private Double longitude = 48.8588336;
private Double latitude = 2.2769956;
/*code*/
latitude= (Double) webengine.executeScript("latitude");

JavaSript

let longitude;
  let latitude;
  var map = L.map('map').setView([longitude,latitude], 13);

the Longitude and latitude didn’t send to Js.

Remove array map and handlers from render operation

I wrote this code a while ago and I came back to try and clean it by removing the map array and handlers out of the render operation but I keep getting syntax errors. How could I go about this? I’m getting the same error: Syntax error: Unexpected token, expected “,” but varying on how I try to separate it.

 if (!sales) {
    return (
      <div>
        <Spinner />
      </div>
    );
  }

 return (
    <ul>
      {sales.map((result) => {
        const {
          sale_id,
          buyer,
          seller,
          listing_price,
          listing_symbol,
          created_at_time,
        } = result;

        function HandleBuyerClick() {
          window.location = '/user/' + buyer;
        }
        function HandleSellerClick() {
          window.location = '/user/' + seller;
        }

        if (buyer !== null) {
          return (
            <Card>
              <li key={sale_id}>
                <h3>
                  <Transaction>
                    <Button onClick={HandleSellerClick}>{seller}</Button>
                  </Transaction>{' '}
                  just sold item number
                  <Transaction>
                    <Button>{sale_id}</Button>
                  </Transaction>{' '}
                  to
                  <Transaction>
                    <Button onClick={HandleBuyerClick}>{buyer}</Button>
                  </Transaction>{' '}
                  for <Transaction>{formatNumber(listing_price)}</Transaction>{' '}
                  {listing_symbol} at {parseTimestampJM(created_at_time)}
                </h3>
              </li>
            </Card>
          );
        }
      })}
    </ul>
  );

Javascript show only X amount from array.map with option to show all

I have a table row, and inside a cell I want to display values mapped from an array (yes in a single cell). I have too many values in this array, so I want to only show 3 and then have a button to show the rest if clicked. How can I go about to achieve this? Current code:

<TableCell align="right">
 {row[headCell.id].map((obj) => (
  <>
   {obj}
   <br />
  </>
 ))}
</TableCell>

intersection observer works only for the first video

I need to pause a video if it is not in view
the below code works only for the first video in list
how to make it working for all .bvideo ?

<video class='bvideo' src='a.mp4' poster='a.jpg' preload='none' controls></video>
<video class='bvideo' src='b.mp4' poster='b.jpg' preload='none' controls></video>
<video class='bvideo' src='c.mp4' poster='c.jpg' preload='none' controls></video>

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if(!entry.isIntersecting){entry.target.pause();}
  });
});

$(document).ready(function(){
    io.observe(document.querySelector('.bvideo'));
});

automating / overriding / extending prefix in console.log for debugging

Anyone have a good solution to extending console.log so that it auto prints class name and method as a prefix? I’m using web components and use strict is turned on.

someFunction() {
  let varA = "hello"
  console.log(this.constructor.name, "someFunction", {varA})
}

Would like to automate this part: this.constructor.name, “someFunction”, …

arguments.callee.name will print the function name, but no longer works with strict mode turned on.
Extending console.log in a centralized location via:

export var log = function(){
  var args = Array.prototype.slice.call(arguments);
  args.unshift(this.constructor.name + ": ");
  console.log.apply(console, args);
}

does not work as this.constructor.name does not print the correct context and if it’s not in a web component, it doesn’t work at all.
Extending console.log in each web component defeats the purpose (or half of it).
Could fold a function that extends console.log in the build for each web component but would still have the problem of not being able to call arguments.calleee.
Using lit-element, but this is a native javascript issue.

How to Android WebView video fullscreen lock orientation

Screen orientation lock (screen.orientation.lock()) is not working in android webview.

function lockLandScape() {
    console.log(JSON.stringify(screen.orientation.lock))
    if (screen.orientation && screen.orientation.lock) {
      screen.orientation.lock('landscape');
    }
}
function unlockLandScape() {
    if (screen.orientation && screen.orientation.unlock) {
        screen.orientation.unlock()
    }
}   
function videoFullScreen(elem){
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { 
      elem.msRequestFullscreen();
    }
    elem.classList.add("fullscreen");
    lockLandScape()
}

Where elem is video element in webview.