How to serve static HTML files with vanilla javascript including submodules?

I want to serve a static html file with elements defined in a javascript file using imports from submodules. How is this possible with vanilla JS? Or do I need some bundling tools and / or other frameworks? Example code structure to illustrate my intention:

index.html

<html>
  <div id="screen">
    <div id="grid"></div>
  </div>
  <h1>Example</h1>
  <body>
    <script type="module" src="index.js"></script>
  </body>
</html>

index.js

import { buildGrid } from "./buildGrid.js"
var http = require("http");
http
  .createServer(function (req, res) {
    fs.readFile(__dirname + req.url, function (err, data) {
      if (err) {
        res.writeHead(404);
        res.end(JSON.stringify(err));
        return;
      }
      res.writeHead(200);
      res.header("Content-Type", "application/javascript");
      res.end(data);
    });
  })
  .listen(8080);

buildGrid();

buildGrid.js

export function buildGrid() {
    let grid = document.getElementById("grid");
    let cell = document.createElement("div");
    cell.className = "cell";
    cell.textContent = "test;
    grid.appendChild(cell);
}

style.css

body,
html {
  background: #111;
  color: white;
}
#screen {
  display: flex;
  flex-direction: column;
}
.cell {
  width: 30px;
  height: 30px;
  background: #2d2f34;
}

Can’t get eventListener to display value in console

Hey guys im new to javascript and trying to get a better understanding of it, i am trying to make a 8 ball project and currently just to see if it works get it to display in the console but all i recieve is that it is undefined

const predictions = ['Ask again later, Better not tell you now, Cannot predict now, Concentrate and ask again'];
const btn = document.getElementById('btn')

btn.addEventListener('click', function() {
    console.log(predictions[randomNumber])
});




function randomNumber() {
    return Math.floor(math.random() * predictions.length)
};
body {
    background: linear-gradient(to right, #06932d, #000000);
    display: flex;
    align-items: center;
    justify-content: center;
}

#prediction {
    position: fixed;
    top: 300px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='8-ball.css'rel="stylesheet">
    <script defer src="8-ball.js"></script>
    <title>8 Ball</title>
</head>
<body>
    <div id="title">
        <h1>Try the Magic 8 Ball!</h1>
    </div>

    <div id="btn">
        <button>Try Me!</button>
    </div>

    <div id="prediction">
        <p>text</p>
    </div>
</body>
</html>

Can you help me understand why the code is not working correctly? (Vue,js)

I have a code, when you click on a new task, the first one is crossed out, I can’t understand why (Photo below)
enter image description here enter image description here

When you click on a new task, the first one is crossed out, and the one I click on should be

<template>
<h4>Today Tasks</h4>  
<div class="tasks">
<div 
      class="task"
      :class="{ completed: task.isCompleted }"
      v-for="task in tasks"
      :key="task._id"
      @click="completedHandler(task._id)"
   >

  <div 
        class="round"
        :class="{ 
        business: task.type === 'business', 
        personal: task.type === 'personal',
        }"
        
        ></div>

    <span>{{task.name}}</span>
  </div>
</div>
  <div class="add-task">
    <input type="text" placeholder="Название задачи" v-model="taskName" />
    <button @click="addTask">+</button>
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  data(){
    return {
      taskName: "",
      tasks: [{
        _id: "wadawdawdwa",
        name: "Create to do app in Vue js",
        isCompleted: false,
        type: "personal",
      }
      ]
    }
  },
    methods:{
      completedHandler:function(taskid){
        const currentTask=this.tasks.find((t)=> t._id=taskid);
        currentTask.isCompleted = !currentTask.isCompleted;
    },

    addTask: function(){
      this.tasks.push({
        _id: Math.random().toString(36).substring(2, 7),
        name: this.taskName,
        isCompleted: false,
        type: "personal",
       });
    },
  },
};
</script>

how can i setup my Fish data visualization using a bar chart? any ideas?

sketch.js
weight = [];
inches = [];

function preload() {
  table = loadTable("fish.csv", "csv", "header");
}

function setup() {
  createCanvas(400, 500);
  numberOfRows = table.getRowCount();
  numberOfColumns = table.getColumnCount();
}
fish.csv
Fish name,Weight,Inches
Black Drum,1,12
Almaco Jack,2,16
Grouper Snowy,2,12
Albacore tuna,3,20
Red Drum,3,19
Rainbow Trout,3,19
Sablefish,3,11
Grouper Tiger,4,15
Skipjack Tuna,5,20
Sockeye Salmon,5,17
Atlantic Bonito,6,27
Horse-eye Jack,8,45
Atlantic Cod,8,30
Palometa Jack,10,35
Rockfish,10,12
Pink Salmon,10,11
Lookdown,12,30
Sand Seatrout,15,31
Summer Flounder,20,17
White Grunt,22,32
Red Porgy,30,20
Sounthern Flounder,35,4
Atlantic Croaker,50,45
Lesser Amberjack,51,45
Black Sea-Bass,51,6
Saucereye Porgy,70,52
Bnaded Rudderfish,80,47
Great Barracuda,100,60
Chum Salmon,130,60

I am using pj5 editor for this project. I used fishes weight and inches. But I am not sure
how can I set up my sketch.js file to add the code and also some images of the fish to show
as in bar chart. Any ideas?

 [Text](https://editor.p5js.org/stupiduseless8/sketches/1TCFE2WxV)

React Native, Fetch specific data from API Results

I am making an app using React Native to show railway PNR status after entering PNR Number using API.

API Results,

Array [
  Object {
    "data": Object {
      "boarding_station": Object {
        "day_count": "X",
        "departure_time": "XX:XX",
        "station_code": "XXX",
        "station_name": "XXXXX",
      },
      "booking_date": "XX/XX/XXXX",
      "chart_prepared": X,
      "class": "XX",
      "date": "XXXX-XX-XX",
      ~~~~~~~~~~~~~~~~~~~~~~
      "passenger": Array [
        Object {
          "bookingBerthCode": "XX",
          "bookingBerthNo": "XX",
          "bookingCoachId": "XX",
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        },
      ],
      "pnr_number": "XXXXXXXXXXX",
      "quota": "XX",
      "train_name": "XXXX",
      "train_number": "XXXX",
    },
    "message": "Success",
    "status": true,
    "timestamp": XXXXX,
  },
]

Code

const [apiResults, setAPIResults] = useState([])

const fetchPNRStatus = async () => {
        try {
            const response = await fetch(`API Link`, headers)
            const results = await response.json()
            setAPIResults([results])
            console.log(apiResults)
        } catch (error) {
            console.log(error.message)
        }
    }

console.log(apiResults) displays the API results as given above. But I want to get specific values like departure_time under boarding_station array or booking_date or
bookingBerthCode under passenger array etc.

How to do that?

How can I make my hamburger menu to appear?

I know that maybe it´s sth easy to build, but I can´t make my hamburger menu appear when pressing the icon. I think that the problem is in the javascript part. here is my code:

html:

 <section id="header">
        <a href="#"><img id="icon-home" src="iconos/menu.jpg" alt=""></a>
        <div>
            <ul id="navbar">
                <li><a class="active" href="index.html">Home</a></li>
                <li><a href="shop.html">shop</a></li>
                <li><a href="blog.html">blog</a></li>
                <li><a href="about.html">about</a></li>
                <li><a href="contact.html">contact</a></li>
                <li ><a href="cart.html"><i><svg xmlns="http://www.w3.org/2000/svg"
            </ul>
        </div>
        <div id="mobile">
            
            <a href="cart.html"><i><svg xmlns="http://www.w3.org/2000/svg" 

        </div>
    </section>

css: Here I hide the menu when the screen is +800 px,

#mobile{
    display: none;
    align-items: center;
}  
@media (max-width:799px){
    #navbar{
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: flex-start;
        position: fixed;
        top: 0;
        right: -300px;
        height: 100vh;
        width: 300px;
        background-color: #fefefe;
        box-shadow: 0 40px 60px rgb(0, 0, 0, 0.1);
        padding: 80px 0 0 10;
    }

    #navbar.active{
        right: 0px;
    }

    #navbar li{
        margin-bottom: 25px;
    }
    #mobile{
        display: flex;
        align-items: center;
    }    
    #mobile i{
        color: #1a1a1a;
        font-size: 24px;
        padding-left: 20px;

    }
}

js: im quite sure that the problem should be here (I do not have more details to explain I think)

const bar  = document.getElementById('bar');
const nav = document.getElementById('navbar');

if (bar) {
    bar.addEventListener('click', () => {
        nav.classList.add('active');
    })
};

It would be realy useful any help, than u!!!

CanvasJS: How does dataPoints really work?

I need to know how dataPoints works in canvasJS. For example: i know that if i feed dataPoints a json file that is completely comprised of x and y points, it will chart them just fine. However, I want to know if that is the only form of data it can take. how does it parse through the data and decide which point is an X point and which one is a Y point? I cant find documentation on this and if I could it would give me answers to HOW I should be cleaning and organizing my JSON files so they can be fed to dataPoints and graphed easily. Thank you!

discord.js v13: how to make a role with the highest available position

I want to do a mute command where the bot creates a role and puts it in the highest position it can.

Here’s my code:

run: async (client, message, args) => {
    if (!message.guild.me.permissions.has("MANAGE_ROLES")) return message.channel.send("Eu não tenho perm: `MANAGE_ROLES`");

    let rolecreate = message.guild.roles.create({ name: "", permissions: [], reason: "" }).then((create) => message.member.roles.add(create));
};

How do I make a second row instead of list for collapsed content in Tabulator?

I’m trying to set up a second row to appear instead of formatting the extra columns as a list. It looks like the way Tabulator does this is by making a table with the column titles bolded on the left with the value on the right. However, this means I can’t resize the column for the collapsed content. I’m hoping to at least change the formatting so the table shows as an actual table and not a list.

I run Tabulator on my own machine so that I can change some of the css and js directly without having to add any extra code withing the HTML file. I believe this is the snippet of code I need to change in order to make the collapsed content show as an extra row (or at least a table with multiple columns) rather than a list:

key: "formatCollapsedData",
      value: function formatCollapsedData(data) {
        var list = document.createElement("table");
        data.forEach(function (item) {
          var row = document.createElement("tr");
          var titleData = document.createElement("td");
          var valueData = document.createElement("td");
          var node_content;
          var titleHighlight = document.createElement("strong");
          titleData.appendChild(titleHighlight);
          this.langBind("columns|" + item.field, function (text) {
            titleHighlight.innerHTML = text || item.title;
          });

          if (item.value instanceof Node) {
            node_content = document.createElement("div");
            node_content.appendChild(item.value);
            valueData.appendChild(node_content);
          } else {
            valueData.innerHTML = item.value;
          }

          row.appendChild(titleData);
          row.appendChild(valueData);
          list.appendChild(row);
        }, this);
        return Object.keys(data).length ? list : "";
      }
    }]);

    return ResponsiveLayout;
  }(Module);

Thank you in advance for any help!

How to make vertical line when hovering cursor (Chart js)

Hay everyone, I am trying to make vertical line drawing on chart when I hover my mouse on some dot.
I saw some solutions online but I didn’t figer it out how to implement it on my code because I am very new at react js

this is an example of chart that has that vertical line that I am referring to – vertical line chart

Can someone help me do this?

This is my code:

import React, { Component } from "react";
import "../App.css";
import { Line } from "react-chartjs-2";
import { Chart as ChartJS, Filler } from "chart.js/auto";

export default class Chart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mapRecv: props.data[0],
      type: props.data[1],
    };
  }

  render() {
    return (
      <>
        <Line
          className="chart"
          data={{
            labels: this.state.mapRecv["stockChartXValues"],
            datasets: [
              {
                label: `${this.state.type} Price USD`,
                data: this.state.mapRecv["stockChartYValues"],
                fill: true,
                backgroundColor: ["rgba(75, 192, 192, 0.2)"],
                borderColor: "rgba(75, 192, 192, 1)",
                borderWidth: 2,
              },
            ],
          }}
          options={{
            scales: {
              x: {
                grid: {
                  drawOnChartArea: false,
                },
              },
              y: {
                beginAtZero: false,
                lineHeight: 1.2,
                grid: {
                  drawOnChartArea: false,
                },
                type: "linear",
                display: true,
              },
            },
            position: "right",
            showLine: true,
            elements: {
              point: {
                radius: 0,
              },
            },
            plugins: {
              legend: {
                display: false,
              },
            },
            interaction: {
              intersect: false,
              mode: "index",
            },
            spanGaps: true,
          }}
        />
      </>
    );
  }
}

How is putting “is” in front of booleans any different from Hungarian Notation? [closed]

Hungarian Notation is pretty universally disliked but I can’t help but notice that many programmers, especially in Typescript or Javascript, still put “is” “should” “has” and “did” in front of variables to indicate that they are booleans. I don’t understand why this practice persists and why the people writing this code don’t just take their conclusions all the way and put “str” “arr” and “obj” in front of variables too. What’s the difference and why do only booleans get a special Hungarian designation in so many people’s source code? I don’t mind Hungarian Notation. What I do mind is the logical inconsistency and doing things two separate ways.

JS equivalent for Golang’s strconv.Quote

Given a YAML like this:

--- 
body: "something else"
path: site:^example.com?"something"..."something"
title: "How to do this"

parsing it using yaml-ast-parser, it results in an invalid YAML because to he period in the regex and the quotes. I can extract the value of path and double quote it with strconv.Quote and that results in a final YAML like this:

--- 
body: "something else"
path: "site:^example\.com?"something"..."something""
title: "How to do this"

However, strconv.Quote is a golang method and this is a javascript project. Does anyone know a way I can achieve strconv.Quote in a javascript environment.

Is there a way to not repeat myself in if functions? [duplicate]

const navTitle = document.querySelectorAll(".nav-link");
btnLang.addEventListener("click", () => {
  if (btnEnglish.classList.contains("hiddden")) {
    const attr = btnPortuguese.getAttribute("language");
    navTitle.forEach((el, index) => (el.textContent = data[attr].navbar[index]));
  } else {
    const attr = btnEnglish.getAttribute("language");
    navTitle.forEach((el, index) => (el.textContent = data[attr].navbar[index]));
  }
});

I can’t use this syntax below because it gives me an error.

const navTitle = document.querySelectorAll(".nav-link");
btnLang.addEventListener("click", () => {
  if (btnEnglish.classList.contains("hiddden")) {
    const attr = btnPortuguese.getAttribute("language");
  } else {
    const attr = btnEnglish.getAttribute("language");
  }
  navTitle.forEach((el, index) => (el.textContent = data[attr].navbar[index]));
});

Is there a way that I can access the attr variable? I already tried to use ATTR as global variable but it didn’t work.