javascript – call a function from another function

For example, in my html i have:

<script>
   var mouvement = 1;
   makemouvement(mouvement);
</script>

<script>
  function test(){
    function subtest1(){
      //...
    };
    function subtest2(){
      //...
    };
    function makemouvement(mouvement){
      alert(mouvement);
      //...
    };
  }
</script>

how can I call the “makemouvement” function (which is inside test function) from my first script plz?

NextResponse.json possibly corrupting json syntax

Running nextjs 13.5.3 and working an api route handler under /app

The route handler has a few functions but primarily fetches from a cms and returns the response. IDs appear on the client side hashed, so one of its functions is to unhash ids from a request, and hash them in the response. For the sake of debugging and solving this problem, I am now just manually changing the id values to a string, from an integer, which is what the hashing function did.

Problem

The client receives responses from the route handler just fine if I don’t modify the response. But if I change the value of id in the route handler (for the sake of hashing it), the browser is unable to parse the response json when I attempt const data = await response.json();

Uncaught (in promise) SyntaxError: Expected ‘:’ after property name in
JSON at position 2269 (line 1 column 74)

Route Handler Simplified to minimal working version

export async function POST(request, params) {

    const serviceRes = await fetch('https://someservice.com/api');

    ... check status of response is ok ...
    ... check if json is returned and if it is, parse it ...

    const serviceData = await serviceRes.json();

    // Modify the value of id, if it exists

    if (serviceData && serviceData.data && serviceData.data.id) {
        serviceData.data.id = 'test';
    }

    const res = NextResponse.json(serviceData, {
        status: serviceRes.status,
        headers: serviceRes.headers,
    });

    return res;

}

serviceData sample, after changing id

{
    "data": {
        "id": "asdasd", // this was an integer, like 4278
        "title": "Hello World",
        "content": "This is a test content",
        "tagging": []
    }
}

Further Tests

In the route handler, just after modifying serviceData.data.id, I’ve added:

console.log("serviceData", serviceData);
console.log("stringified", JSON.stringify(serviceData));

And am seeing no issue with the object or json. I’ve validated them fine. Which is why I’m wondering if the Nextresponse.json is the issue?

The column where the issue occurs, according to the error statement is where the colon appears on the final key, tagging. The error seems to think there’s no colon there, but it appears in the console logs fine. And I’m not modifying tagging, so it’s an unusual situation.

I’ve tried testing for non-mutating versions using spread operators but the same error occurred.

Again, if I don’t modify any value in serviceData, the browser parses the json fine. I’m stumped

How to calculate totalcost which belong to same group in javascript

I have json data like following, and what I am trying is to calculate total cost of each year based on domain nameand insert those key:values in nested property “Domain” i.e calculate total cost in each year based on group , for example I have data like this,

[ {
    "2033": 100,
    "2034": 100,
    "2035": 100,
    "2036": 100,
    "2037": 0,
    "2038": 0,
    "2039": 0,
    "Domain": {
      "name": "Commercial",
      "totalcost": 0
    },
    "totalcost": 400
  },
  {
    "2033": 100,
    "2034": 100,
    "2035": 100,
    "2036": -100,
    "2037": 100,
    "2038": 100,
    "2039": -100,
    "Domain": {
      "name": "Commercial",
      "totalcost": 0
    },
    "totalcost": 300
  },
 ...
]

then I want to convert this data to ,

[{
    "2033": 100,
    "2034": 100,
    "2035": 100,
    "2036": 100,
    "2037": 0,
    "2038": 0,
    "2039": 0,
    "Domain": {
      "name": "Commercial",
      "2033": 200, //row1["2033"]+row2["2033"]
      "2034": 200,
      "2035": 200,
      "2036": 0,
      "2037": 100,
      "2038": 100,
      "2039": -100,
      "totalcost": 700  // row1["totalcost"]+row2["totalcost"]
    },
    "totalcost": 400
  },
  {
    "2033": 100, 
    "2034": 100,
    "2035": 100,
    "2036": -100,
    "2037": 100,
    "2038": 100,
    "2039": -100,
    "Domain": {
      "name": "Commercial",
      "2033": 200,    
      "2034": 200,
      "2035": 200,
      "2036": 0,
      "2037": 100,
      "2038": 100,
      "2039": -100,
      "totalcost": 700  
    },
    "totalcost": 400
  },
 ...

Chart.js 4.4.2, how to have mutiple datapoints/labels in the tooltips when hovering over a datapoint?

As the title explains, I am trying to crate a report using chart.js to give the user a grahical representation of the data that they have searched for in the system, I am currently able to get the data to display on the canvas.

I have the data being provided to the JS function in a JSON format from the backend of the system. I have the main data that is building the pie chart with other data needing to be added to the tooltips to give further explanation on that data point.

How would i go about this as looking online hasnt given any viable result that has worked?

I have attached a simplified version of the code below with the data being displayed how its produced in the system.

var ctx = document.getElementById('myChart').getContext('2d');

var data = {
  title: "Booking duration between 01/08/2023 and 29/03/2024",
  labels: ["0 - 6 days", "7 - 13 days", "14 - 20 days", "21 - 27 days", "28 - 34 days"],
  datasets: [{
    data: [2126, 430, 51, 20, 44],
    backgroundColor: ["#82B6EB", "#434348", "#94EE7E", "#F3A15E", "#8385E8"],
    datalabels: ["79.6 %", "16.1 %", "1.91 %", "0.75 %", "1.65 %"],
    databooking: ["( 2126 bookings)", "( 430 bookings)", "( 51 bookings)", "( 20 bookings)", "( 44 bookings)"],
    hoverOffset: 20
  }]
};

var myChart = new Chart(ctx, {
  type: 'pie',
  data: data,
  options: {
    tooltips: {
      callbacks: {
        label: function(tooltipItem, chartData) {
          var dataset = chartData.datasets[tooltipItem.datasetIndex];
          var currentValue = dataset.data[tooltipItem.index];
          var dataLabel = dataset.datalabels[tooltipItem.index];
          var dataBooking = dataset.databooking[tooltipItem.index];
          return 'Value: ' + currentValue + ' ' + dataLabel + ' ' + dataBooking;
        },
        title: function(tooltipItems, data) {
          return data.title;
        }
      }
    }
  }
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>

<div id="_Chart">
  <canvas id="myChart" style="width:1700px; max-height: 550px;"></canvas>
</div>

Reimplement HTML Media Tag Fetching without a tag using Media Source API

I am trying to re implement the fetching stack of a video tag before the tag is mounted.

Media Source API seems to be the right solution to do this, but it does not seems to open if I don’t attach it to a media tag. (not receiving the sourceopen event).

My requirement are that I can :

  • Open one or multiple source and fill them as I want using partial fetching on my video(s) (that I control).

  • I can as I go attach and detach the Sources to a video player.

Is it possible to do this with Media Source ?

Is there a better way to do it ?

Jest :: Mock navigator.Useragent is not working in browser as well as in test case

Im trying to change the navigator userAgent through jest and for different agent we have different code to be executed.It seems not possible to override.Even in the browser im not able to overrride

Object.defineProperty(window.navigator, 'userAgent', { value: 'xxx', writable:true, configurable: true });
VM517:1 Uncaught TypeError: Cannot redefine property: userAgent
    at Function.defineProperty (<anonymous>)
    at <anonymous>:1:8

How to make npx run the js cli script in windows?

The Problem – My npx scaffolding script works fine on linux but doesn’t work on windows. However I see a lot packages which runs fine on windows but I couldn’t find out what they are doing differently. I asked AI tools (Chatgpt/Gemini) they couldn’t provide a solution.

What happens on linux? – Script is normally executed by node and works fine.
What happens on windows? – It just opens a new command prompt window doing nothing.

  • I created a npm package @reuk/start for scaffolding my commonly used project templates.
  • I intented to use it as npx script. similar to npx create-vite.
  • For this i created a script and added that to the bin field in my package.json -> "bin": "./bin/cli.js". and published the package.
  • Running the script normally like node ./bin/cli.js works perfectly fine. the only problem is when doing npx @reuk/start it is not invoking the script using node.
  • My cli.js has a shebang #!/usr/bin/env node to tell the interpreter to run it using node. I know shebang only works in unix systems and windows doesn’t support it, but how does create-vite work on windows, and why doesn’t mine work despite having the similar code?

What am I doing wrong here? And more importantly how do I make it work cross platform seamlessly?

For reference here is the code –
@reuk/start | create-vite

Course Header Navigation in Moodle

I have a Moodle site. on site I have edumy theme but at particular course/view.php page have alpha theme I need edumy theme only on header of course on course/view.php

I try to modified theme templates to get edumy theme header on alpha theme page

How to use a absolute path svg icon with AdvancedMarker?

Been working on moving on to AdvancedMarker since Marker is deprecated in Google Maps.
I’m trying to migrate a marker but they’re rendered it so complicated for nothing…

I used to have a simple svg marker

   new google.maps.Marker({
       position:loc,
       map:map,
       title: title,
       icon: '/img/marker.svg'
   }); 

Now after migration, I cannot for the life of me figure out how to use the same path for the absolute mess of PinElement.

    const pinElement = new google.maps.marker.PinElement({
        glyph: new URL('/img/marker.svg'),
    });

    new google.maps.marker.AdvancedMarkerElement({
        position: loc,
        map: map,
        title: title,
        content: pinElement
    }); 


    Failed to construct 'URL': Invalid URL

How do I load that URL WITHOUT specifying the domain in the glyph ? We use this in multiple env and so domain can change, that’s the reason I wish to use absolute URL.

How to make javascript UMD module work with Vue 3 (Vite)

I’m working onto a project in vue 2 and now we need to upgrade it to version 3. In this project we use an indispensable internal library, which was built by some people that left the company. And my problem is that i found a script that looks like this:

;(function(root, factory) {

    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
      module.exports = factory();
    } else {
      root.NProgress = factory();
    }

})(this, function() { …

I found out that this is the syntax for an UMD module. This file I include in my index.html file. If i use console.log on the factory parameter, it outputs the function above. But if i use console.log on the root parameter it outputs undefined. In the old project with vue 2, it displays something. Why is this happening and how can i fix it?
I also have multiple files that look like this and the problem is universal.

I also found out on the internet that i should use async or defer when i include the script but it didn’t work. I’m also not that familiar with vite, I’m still researching.

Why does window.open return global object instead of window object? [closed]

I had written a script that interacts with a website.

The script opens numerous tabs which have the same domain as the website.

This has worked well for a few years, but now there is an error.

I’ve noticed my array of new tabs is no longer filled with window objects, instead it’s a mix of window and global objects.

If it’s a window object then I’m able to get the elements for the page, however if it’s a global object I’m unable to do this.

I can only use MS Edge as a browser.

I think this is particular to the website I have to use.

Can reproduce the problem if you got to

oanda

And use the devTools console to run:
w = window.open("https://www.oanda.com/currency-converter/en/?from=GBP&to=EUR&amount=1")

Trying to access the variable w will reveal that it is a global object, but I expect it to be a window object

Trying the above code on a different website, such as stack overflow returns a window object as expected, so why is the behaviour different on oanda.com?

How to set width and height of rect element based on svg width

Hello guys i am making some rect element on a image there is initial width=1861 and height=905 of image i am setting width, height, x and y coordinates according to initial width and height, i am also getting width and height of image from user when user enter width and height with 2:1 aspect ratio rect element width, height, x and y adjusting correctly like image width 600 and height 300 but when user enter width 600 and height 200 the calculations becomes wrong, Please tell me the solution how i achieve this.

const svg = document.querySelector('svg')
const rect1 = document.querySelector('#id1')
const rect2 = document.querySelector('#id2')
const btn = document.querySelector('button')

btn.addEventListener('click', () => {
const width = prompt('enter width')
const height = prompt('enter height')
  const initialWidth = svg.width.baseVal.value
  const initialHeight = svg.height.baseVal.value
  console.log(initialWidth)
  svg.setAttribute('width', width)
  svg.setAttribute('height', height)
  const scaleFactorX = width / initialWidth;
  const scaleFactorY = height / initialHeight
  console.log(scaleFactorX, scaleFactorY)
  rect1.setAttribute('width', rect1.getAttribute('width') / scaleFactorX);
  rect1.setAttribute('height', rect1.getAttribute('height') / scaleFactorY);
  rect1.setAttribute('x', rect1.getAttribute('x') * scaleFactorX);
  rect1.setAttribute('y', rect1.getAttribute('y') * scaleFactorY);
  console.log(rect1.getAttribute('x') / scaleFactorX)
})
<button>resize</button>
<svg width="1861" height="905" xmlns="http://www.w3.org/2000/svg">
  <image href="/someimage.png width="1861" height="905">
  <rect id="id1" width="1861" height="905" x="30" y="60" />

  
  <rect id="id2 x="20" width="50" height="50" y="40" />
</svg>

Partial View loading using javascript : Possible XSS by FORTIFY

I have a js function , which Fortify identified as XSS vulnerable as below. Can someone suggest any solution for this since the method is intensively used in my web system.

I am here trying to call a partialview in ajax and the result html am appending to a specified dom div

My function look like the below

success: function(json) {
    if ((dataType == "json") && (json !== true)) {

    var errorInForm=false;
    for (var i = 0; i < json.length; i++) {
        var value = json[i];

        var errorFieldId = value[0];
        var errorField = $($("#" + errorFieldId)[0]); //this is Fortify error

Add interactive tooltips in networkD3 package in R

I’m working on a project where I’m visualizing a network graph using the networkD3 package in R. The network consists of nodes and edges, represented by two data frames: node_df and edge_df, respectively. The node_df data frame contains information about the nodes, including their IDs, labels, groups, and colors. The edge_df data frame contains information about the edges, including the source and target nodes, as well as edge labels.

I’ve tried various approaches to visualize the network graph and add interactivity to it, adding tooltips to nodes and edges. However, I haven’t been successful on adding the tooltips on the arrows when hovering the mouse.

Here’s a summary of the code I’ve tried so far:

Data

> head(edge_df, 10)
   id from to  rel label penwidth       color fontname fontsize weight constraint
1   1    2 16 <NA>   183 5.000000 dodgerblue4    Arial       10      1       TRUE
2   2    3  6 <NA>     1 1.021858 dodgerblue4    Arial       10      1       TRUE
3   3    3 11 <NA>    10 1.218579 dodgerblue4    Arial       10      1       TRUE
4   4    3 17 <NA>     5 1.109290 dodgerblue4    Arial       10      1       TRUE
5   5    3 19 <NA>     2 1.043716 dodgerblue4    Arial       10      1       TRUE
6   6    4  4 <NA>     2 1.043716 dodgerblue4    Arial       10      1       TRUE
7   7    4 21 <NA>     1 1.021858 dodgerblue4    Arial       10      1       TRUE
8   8    5 17 <NA>    17 1.371585 dodgerblue4    Arial       10      1       TRUE
9   9    6  6 <NA>     1 1.021858 dodgerblue4    Arial       10      1       TRUE
10 10    6 10 <NA>     5 1.109290 dodgerblue4    Arial       10      1       TRUE
> head(node_df, 10)
   id type                     label     shape color_level          style   fontcolor       color                   tooltip
1   1 <NA>                       End    circle         Inf rounded,filled      brown4      brown4       ARTIFICIAL_ENDn183
2   2 <NA>                     Start    circle         Inf rounded,filled chartreuse4 chartreuse4     ARTIFICIAL_STARTn183
3   3 <NA>          Analyze Donen18 rectangle  0.08333333 rounded,filled       black        grey          Analyze Donen18
4   4 <NA>               Approvedn3 rectangle  0.01388889 rounded,filled       black        grey               Approvedn3
5   5 <NA> Back from Developmentn17 rectangle  0.07870370 rounded,filled       black        grey Back from Developmentn17
6   6 <NA>                Backlogn9 rectangle  0.04166667 rounded,filled       black        grey                Backlogn9
7   7 <NA>              Cancelledn1 rectangle  0.00462963 rounded,filled       black        grey              Cancelledn1
8   8 <NA>               Closedn138 rectangle  0.63888889 rounded,filled       white        grey               Closedn138
9   9 <NA>           Dispatchedn166 rectangle  0.76851852 rounded,filled       white        grey           Dispatchedn166
10 10 <NA>                 Donen216 rectangle  1.00000000 rounded,filled       white        grey                 Donen216
   penwidth fixedsize fontname fontsize fillcolor                     Group
1       1.5     FALSE    Arial       10     white                       End
2       1.5     FALSE    Arial       10     white                     Start
3       1.5     FALSE    Arial       10   #ECE7F2          Analyze Donen18
4       1.5     FALSE    Arial       10   #FFF7FB               Approvedn3
5       1.5     FALSE    Arial       10   #ECE7F2 Back from Developmentn17
6       1.5     FALSE    Arial       10   #FFF7FB                Backlogn9
7       1.5     FALSE    Arial       10   #FFF7FB              Cancelledn1
8       1.5     FALSE    Arial       10   #74A9CF               Closedn138
9       1.5     FALSE    Arial       10   #3690C0           Dispatchedn166
10      1.5     FALSE    Arial       10   #034E7B                 Donen216

Code

# Add a dummy "Group" column to nodes dataframe
node_df$Group <- node_df$label

# 
edges_net <- edge_df[, c("from", "to", "label")]
colnames(edges_net) <- c("from", "to", "title")

nodes_net <- node_df[, c("id", "label", "Group", "fillcolor")]
colnames(nodes_net) <- c("id", "node_label", "Group", "nodes_color")

# Subtract 1 from the "from" and "to" columns to zero-index them
edges_net$from <- edges_net$from - 1
edges_net$to <- edges_net$to - 1

# set node size
nodes_net$NodeSize <- 20

# JS 
clickJS <- "
d3.selectAll('.xtooltip').remove(); 
d3.select('body').append('div')
  .attr('class', 'xtooltip')
  .style('position', 'absolute')
  .style('border', '1px solid #999')
  .style('border-radius', '3px')
  .style('padding', '5px')
  .style('opacity', '0.85')
  .style('background-color', '#fff')
  .style('box-shadow', '2px 2px 6px #888888')
  .html('name: ' + d.name + '<br>' + 'group: ' + d.group)
  .style('left', (d3.event.pageX) + 'px')
  .style('top', (d3.event.pageY - 28) + 'px');
"
# plot network
my_network<- networkD3::forceNetwork(
  Links = edges_net,
  Nodes = nodes_net,
  Source = "from",
  Target = "to", 
  Value = "title", 
  NodeID = "node_label",
  Group = "Group",
  colourScale = networkD3::JS("d3.scaleOrdinal(d3.schemeCategory20);"),
  linkDistance = 300,
  linkWidth = networkD3::JS("function(d) { return Math.sqrt(d.value);}"),
  radiusCalculation = networkD3::JS(" Math.sqrt(d.nodesize)+6"),
  Nodesize = "NodeSize",
  charge = - 30,,
  linkColour = "black",
  opacity = 0.8,
  zoom = T,
  legend = T,
  arrows = T,
  bounded = T, 
  opacityNoHover = 1.5,
  fontSize = 12,
  clickAction = clickJS
# 
)

# Increase the size of nodes
my_network$x$width <- '1200px'
my_network$x$height <- '800px'


# Get the target variable in fn$x$links (an integer id) to show up as a tooltip when user hovers over a link (i.e. edge) in the graph
fnrender <- htmlwidgets::onRender(
  my_network,
  '
  function(el, x) {
    d3.selectAll(".link").append("svg:title")
      .text(function(d) { return d.source.name + " -> " + d.target.name; })
  }
  '
)
# display the result
fnrender

Produced graph

network

The objective of my project is to create an interactive network visualization where users can hover on nodes to view additional information and hover over edges to see edge labels.