My external Javascript file is not working in the HTML program, how to fix it?

I am using an online free webspace, and I’ve scripted a JavaScript file into the main HTML file, but the JavaScript file isn’t executing.

I don’t know JavaScript, but I typed the Python code and used a Python-to-JavaScript code translator online.
The JavaScript code shows no errors. The code is a choice game, meaning it has many inputs, but the JavaScript file doesn’t even run. How do I solve this?

<!doctype html>

<html>
    <head>
        <meta charset="utf-8">

        <title>April Days</title>

        <!-- Load external CSS styles -->
        <link rel="stylesheet" href="styles.css">

    </head>

    <body>

        <h1>The Beginning of a New World</h1>

        <!-- Load external JavaScript -->
        <script type="text/javaScript "src="test.js"></script>
    </body>

</html>

I need guidance including JS into a HTML file with tags

I need some guidance, since I’m stuck and can’t figure out how to simply include JS code in a html file. I’ve read multiple threads and articles, and have been struggling with getting this to work.

I have copied the HTML/CSS/JS code from codepen and pasted it into a html file.
https://codepen.io/jona09h3/pen/mdKOGxR

The issue is the JS code doesn’t execute.
Please take a look:

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Typewriter</title>
<script>
class TypeWriter {
  constructor(headline, selector) {
    /*The text content*/
    this.heading = headline;

    /*The element with the text content*/
    this.elemSelector = selector;

    /*I'm showing the "cursor" using borderRight.*/
    gsap.set(".blinkCursorEnd", {
      borderRight: "2px solid black"
    });

    /*Set this width to the size of the startingCursor, to make it show.*/
    gsap.set(this.elemSelector, {
      width: "2px"
    });

    gsap.set(".blinkCursorStart", {
      borderRight: "2px solid black",
      opacity: 1
    });

    /*The starting cursor animation. When complete to the actual typeeffect.*/
    gsap.to(".blinkCursorStart", {
      borderRightColor: "transparent",
      duration: 0.5,
      /*Change repeat to make the initial animation shorter or longer*/
      repeat: 10,
      yoyo: true,
      ease: "steps(1)",
      onComplete: () => {
        this.makeTypeWritingEffect();
      }
    });
  }

  makeTypeWritingEffect() {
    /*Hiding the first cursor*/
    gsap.to(".blinkCursorStart", {
      opacity: 0
    });

    /*Showing the second cursor, making it run in an infinite loop*/
    gsap.to(".blinkCursorEnd", {
      borderRightColor: "transparent",
      duration: 0.5,
      repeat: -1,
      yoyo: true,
      /*Change/remove this ease if you want the cursor to fade instead.*/
      ease: "steps(1)"
    });

    /*The actual text being animated.*/
    gsap.to(this.elemSelector, {
      width: `${this.heading.length + 0.2}ch`,
      duration: 2,
      ease: `steps(${this.heading.length})`
    });
  }
}

window.addEventListener("load", function () {
  let typeWriter = new TypeWriter(
    document.querySelector("h2").textContent,
    document.querySelector("h2")
  );
});

</script>
<style>
    h2{
   white-space: nowrap;
  
  /* Hides the text content of h2 as default. The whole content would show right away with this not here.  */
   overflow: hidden;
  
  /*It needs a monospaced font to work best. Have tested it with Source Code Pro aswell.*/
  font-family: monospace;
}
</style>
</head>
<body>
<h2>
<!-- The starting blink cursor -->
 <span class="blinkCursorStart"> </span>
   This is a typing test.
  
<!-- The end cursor  -->
<span class="blinkCursorEnd"> </span>
</h2>
</body>
</html>

I have also tried adding:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> following the title tag. And moving the <script>...</script> to the body instead of header. No difference.

I cannot use the <script src="... attribute and need the code to be in the html file.

What have I not understood and what am I doing wrong ?

Thanks,

How to display chart when it’s clicked on the circle on leaflet map usin vanilla js

I’m trying to put three functions that collect data and draw a chart.js when a circle on the map is clicked in leaflet.

This is my circle(marker):

const station = L.circle([X, Y], {
          color: color,
          fillColor: fillColor,
          fillOpacity: 0.5,
          radius: 2000,
        }).on('click', function() {
          showChart();
          listDataDates(mikeDates);
          mikeChart(mikeData);
        }).addTo(map);
        station.bindPopup(`${nameBg} (Max level Mike11: ${maxLevel11}) (Max level SURFEX-RAPID: ${maxLevelFW})`);

Next function showChart() get the name and send it to the api url like parameter to get dates from the query:

//Create variables for clicked names and dates 
        let ulNames = document.getElementById('clickedNames');
        let ulDates = document.getElementById('clickedDates');

        ulNames.addEventListener('click', showNames);
        ulDates.addEventListener('click', showDates);

        async function showChart() {

          document.getElementById("nameStation").innerHTML = nameBg;
          document.getElementById("clicked").innerHTML = nameBg;

          const apiUrl = "192.168.0.1:3010/dates?id=" + nameBg;

          const response = await fetch(apiUrl);
          const mikeDates = await response.json();
          dataAPI.dateStation = mikeDates;
          dataAPI.nameStation = nameBg;
          listDataDates(mikeDates);
        }

This function put the dates on the dropdown and put the last date like parameter to the url to get more data for the chart.js

function listDataDates(mikeDates) {
          const formatDate = "YYYY-MM-DD HH:mm";
          //console.log(JSON.stringify(data, null, 2))
          // Loop through each result and append the data.
          mikeDates.floodguard_dates.rows.map((clickedDates) => {
            const fillDates = `
            <li><a class="dropdown-item" href="#">${moment(clickedDates.datprog).format(formatDate)}</a></li>`;
            const item = document.createElement('li');
            item.addEventListener('click', async (e) => {
              if (!e || !e.target || !e.target.innerHTML) {
                alert('Възникна неочаквана грешка !');
                //dataAPI.dateStation = null;
                return;
              }
              if (!dataAPI.nameStation) {
                alert('Моля, изберете местоположение.');
                //dataAPI.dateStation = null;
                return;
              }

              dataAPI.dateStation = e.target.innerHTML;

              const apiUrl = "192.168.0.1:3010/mikealldata?id=" + moment(mikeDates.floodguard_dates.rows[0].datprog).format(formatDate) + "&id2=" + dataAPI.nameStation;

              const response = await fetch(apiUrl)
              const mikedata = await response.json()

              const mike11date = mikedata.floodguard_mikealldata.rows.map((x) => x.datechar)
              //console.log(mike11date)
              const mike11value = mikedata.floodguard_mikealldata.rows.map((x) => x.level_11)
              //console.log(mike11value)

              const mikefwdate = mikedata.floodguard_mikealldata.rows.map((x) => x.datechar)
              //console.log(mikefwdate)
              const mikefwvalue = mikedata.floodguard_mikealldata.rows.map((x) => x.Discharge)
              //console.log(mikefwvalue)

              const mikeFirstCodeWarning = mikedata.floodguard_mikealldata.rows.map((x) => x.ALERT_yellow);

              const mikeSecondCodeWarning = mikedata.floodguard_mikealldata.rows.map((x) => x.ALERT_orange);

              const mikeThirdCodeWarning = mikedata.floodguard_mikealldata.rows.map((x) => x.ALERT_red);

              mike11LabelChart = mike11date;
              mike11DataChart = mike11value;

              mikeFWLabelChart = mikefwdate;
              mikeFWDataChart = mikefwvalue;

              mikeYellowWarning = mikeFirstCodeWarning;
              mikeOrangeWarning = mikeSecondCodeWarning;
              mikeRedWarning = mikeThirdCodeWarning;

              let showCurrChart = document.querySelector(".chart-container");
              showCurrChart.style.display = 'inline';

              mikeChart();

              //document.getElementById("nameStation").innerHTML = "Избрали сте: " + dataAPI.nameStation;
              document.getElementById("dateStation").innerHTML = "Дата на изчесление на прогнозата: " + moment(dataAPI.dateStation).format(formatDate);
            });

            item.innerHTML = fillDates;
            list.appendChild(item);
          });
          // Finally append all the data to the UL.
          ulDates.appendChild(list);

          const fillDate = moment(mikeDates.floodguard_dates.rows[0].datprog).format(formatDate);
          document.getElementById("clicked2").innerHTML = fillDate;
        }

This function destroy and create new chart:

 //Create array for Mike11 and MikeFW dates on labels and values for chart
        var mike11LabelChart = [], mike11DataChart = [];
        var mikeFWLabelChart = [], mikeFWDataChart = [];
        var mikeYellowWarning = [], mikeOrangeWarning = [], mikeRedWarning = [];

        async function mikeChart() {
          //Calling function who fetch the data for charts
          //await getMikeFWData();

          //Create a instance of html chart
          const ctx = document.getElementById('chartVisualizeContainerMike11');
          let child = ctx.lastElementChild;
          if (child) {
            ctx.removeChild(child)
          }

          let canvasElement = document.createElement('canvas');
          canvasElement.id = 'mikeChart';

          ctx.appendChild(canvasElement);

          canvasElement.height = 380;
          //canvasElement.width = 680;
          //canvasElement.aspectRatio = 1;
          const a = new Chart(canvasElement, {
            data: {
              labels: mikeFWLabelChart,
              datasets: [{
                type: 'line',
                label: 'водно количество [куб. м./сек.]',
                data: mikeFWDataChart,
                pointRadius: 1,
                borderWidth: 3.5,
                borderColor: '#00b3ff',
                backgroundColor: "#00b3ff",
                pointBackgroundColor: "#00b3ff",
                pointBorderColor: "rgba(255, 255, 255, 0)",
                pointHoverBackgroundColor: "#00b3ff",
                pointHoverBorderColor: "#00b3ff",
                showToolTips: false,
              }, {
                type: 'line',
                label: 'надморска височина [метри]',
                data: mike11DataChart,
                pointRadius: 1,
                borderWidth: 3.5,
                borderColor: '#754617',
                backgroundColor: "#754617",
                pointBackgroundColor: "#754617",
                pointBorderColor: "rgba(255, 255, 255, 0)",
                pointHoverBackgroundColor: "#754617",
                pointHoverBorderColor: "#754617",
                //pointHoverBorderColor: "#0022ff",
                showToolTips: false,
              }, {
                type: 'line',
                label: 'предупреждение I',
                data: mikeYellowWarning,
                pointRadius: 1,
                borderWidth: 3,
                borderColor: '#eeff00',
                backgroundColor: "#eeff00",
                pointBackgroundColor: "#eeff00",
                pointBorderColor: "rgba(255, 255, 255, 0)",
                pointHoverBackgroundColor: "#eeff00",
                pointHoverBorderColor: "#eeff00",
                showToolTips: false,
              }, {
                type: 'line',
                label: 'предупреждение II',
                data: mikeOrangeWarning,
                pointRadius: 1,
                borderWidth: 3,
                borderColor: '#ff8400',
                backgroundColor: "#ff8400",
                pointBackgroundColor: "#ff8400",
                pointBorderColor: "rgba(255, 255, 255, 0)",
                pointHoverBackgroundColor: "#ff8400",
                pointHoverBorderColor: "#ff8400",
                showToolTips: false,
              }, {
                type: 'line',
                label: 'предупреждение III',
                data: mikeRedWarning,
                pointRadius: 1,
                borderWidth: 3,
                borderColor: '#ff0000',
                backgroundColor: "#ff0000",
                pointBackgroundColor: "#ff0000",
                pointBorderColor: "rgba(255, 255, 255, 0)",
                pointHoverBackgroundColor: "#ff0000",
                pointHoverBorderColor: "#ff0000",
                showToolTips: false,
              },]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,

              scales: {
                x: {
                  ticks: {
                    maxRotation: 90,
                    minRotation: 90
                  }
                }, y: {
                  ticks: {
                    // Include a dollar sign in the ticks
                    callback: function (value, index, ticks) {
                      return value;
                    }
                  }
                }
              }
            }
          })
        };
For now when I using this code I receive error: Uncaught ReferenceError: mikeDates is not defined

when I trying to call listDataDates(mikeDates); in the circle

Is there a way to draw a chart when I click on the circle ?

How to convert a readonly object type to a mutable object type with writable properties in TypeScript?

I have a readonly object type in TypeScript, and I want to convert it to a mutable object type with writable properties. Specifically, I have a constant readonly array d that contains some objects with the following shape:

const d = [
  { id: 1, name: 'b', type: 'c', accessory: 'd' },
  { id: 2, name: 'p', type: 'r', accessory: 'y' },
] as const;

I also have a type G that corresponds to the type of the elements of d:

export type G = typeof d[number];

The resulting G type is readonly and has the following shape:

type G = {
    readonly id: 1;
    readonly name: "b";
    readonly type: "c";
    readonly accessory: "d";
} | {
    readonly id: 2;
    readonly name: "p";
    readonly type: "r";
    readonly accessory: "y";
}

Now, I want to convert the G type back to a mutable object type with writable properties, so that I can modify the properties at runtime. The resulting type should have the following shape:

type WritableG = {
  id: number;
  name: string;
  type: string;
  accessory: string;
};

I have tried to achieve this by creating some generics like the ones below

type Writable1<T> = T extends (infer U)[] ? Writable1<U>[] :
  T extends object ? { -readonly [P in keyof T]: Writable1<T[P]> } :
  T;
type WritableG = Writable1<G>

But this always result to a type like this

type WritableG = {
    id: 1;
    name: "b";
    type: "c";
    accessory: "d";
} | {
    id: 2;
    name: "p";
    type: "r";
    accessory: "y";
}

How can I achieve this in TypeScript that I can convert the type G back to a normal typescript type that would give me something like this again

type WritableG = {
   id: number;
   name: string;
   type: string;
   accessory: string;
}

The example is in this playground

Mantine extended props don’t show up in storybook vite

(Vite config
I want to see my props plus all the mantine props in the storybook but seems like only props defined by me are shown in the storybook

My type files

import {
  InputVariant,
  TextInputProps as MantineTextInputProps,
} from '@mantine/core';

export type MantineTextInputPropsType = MantineTextInputProps &
  React.RefAttributes<HTMLInputElement>;

export interface TextInputProps extends MantineTextInputPropsType {
  title: string;
  description?: string;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  disabled?: boolean;
  variant?: InputVariant;
  isRequired?: boolean;
  maxLength?: number;
  value?: string;
}

My storyBook file

import { Meta, Story } from '@storybook/react';
import { ChangeEvent, useState } from 'react';
import { TextInput as StoryBookTextInput } from './';
import { TextInputProps } from './TextInput';

export default {
  title: 'core/atoms/textInputs/TextInput',
  component: StoryBookTextInput,
} as Meta;

const Template: Story<TextInputProps> = ({ ...args }) => {
  const [value, setValue] = useState('');
  const onChange = (e: ChangeEvent<HTMLInputElement>) =>
    setValue(e.currentTarget.value);
  return <StoryBookTextInput value={value} onChange={onChange} {...args} />;
};

export const TextInput = Template.bind({});

TextInput.args = {
  title: 'Title',
  description: 'This is the description',
  disabled: false,
  gainsightId: 'text-input',
  placeholder: 'Placeholder text',
};


The StoryBook output just displays

  title: string;
  description?: string;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  disabled?: boolean;
  variant?: InputVariant;
  isRequired?: boolean;
  maxLength?: number;
  value?: string;

and not the other mantine props

i tried configuring both vite plugin and storybook main with
‘react-docgen-typescript’

Tried Plugins: @joshwooding/vite-plugin-react-docgen-typescript, react-docgen-typescript-vite-plugin

tried both react doc-gen configs

// .storybook/main.js

module.exports = {
  typescript: {
    check: false,
    checkOptions: {},
    reactDocgen: 'react-docgen-typescript',
    reactDocgenTypescriptOptions: {
      shouldExtractLiteralValuesFromEnum: true,
      propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
    },
  },
};

and

// .storybook/main.js

module.exports = {
  stories: [],
  addons: [],
  typescript: {
    reactDocgen: 'react-docgen-typescript',
    reactDocgenTypescriptOptions: {
      compilerOptions: {
        allowSyntheticDefaultImports: false,
        esModuleInterop: false,
      },
    }
  }
};

Even tried

const { mergeConfig } = require('vite');
const viteTsConfigPaths = require('vite-tsconfig-paths').default;
const reactDocgenTypescript = require('@joshwooding/vite-plugin-react-docgen-typescript');

module.exports = {
  core: { builder: '@storybook/builder-vite' },
  stories: ['../../**/*.stories.mdx', '../../**/*.stories.@(js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-essentials'],
  plugins: [reactDocgenTypescript()],
  typescript: {
    check: false,
    checkOptions: {},
    reactDocgen: 'react-docgen-typescript',
    reactDocgenTypescriptOptions: {
      shouldExtractLiteralValuesFromEnum: true,
      propFilter: (prop) =>
        prop.parent ? !/node_modules/.test(prop.parent.fileName) : true,
    },
  },
  async viteFinal(config, { configType }) {
    return mergeConfig(config, {
      plugins: [
        viteTsConfigPaths({
          root: '../../../',
        }),
      ],
    });
  },
};

Input text has no value or val() or text()

I have a input type=text, see below for the example and all attributes. I can type in the defined space, but there is no way to get what is written inside the input. .val(), .text() and .value all give back undefined or null.

Also, triggers like field.on(“change” f(){}) don’t fire.

Now, this is placed inside an ajax.beginform. When I press a button, I call a function to store the data that has a formcollection as parameter, where this specific field DOES have the typed value. I just need to check whether this field has a value before submitting, so checking it at the function that uses the formcollection is prohibited.

I have no clue why or how to solve this. I know the difference in properties and attributes.
I’m on Razor/c#, but the logic is written entirely in Javascript

the input field

There are no double id’s, typing mistakes or other shenanigans. I isolated this element to test the above mentioned things (like triggers, properties or attributes) but it just stays undefined

Hi i am just trying to switch toggle button on/ off , when onclick event is triggered in table , for a mapped data, but it is not working

here is the table component to render here i am not able to render the icon , but outside the mapping it works usually like it works perfetly , i tried with different options as well….

//here is the table component to render 

export default function RenderTable(props) {

    SinelecTable.propTypes = {
        header: PropTypes.array.isRequired,
        data: PropTypes.arrayOf(PropTypes.array).isRequired,
        className: PropTypes.string
    };

    return (
        <Table responsive className={props.className}>
            <thead>
            <tr>
                {props.header.map((name, idx) => <th key={idx}>{name}</th>)}
            </tr>
            </thead>
            <tbody>
            {props.data.map((row, idx) => {
                if (!props.max || props.max > idx)
                return <tr key={idx}>
                            {row.map((col, cidx) => {
                                    if (isObject(col) && col?.td) {
                                        return <td key={cidx} colSpan={col.colspan}> {col.td}</td>
                                    } else {
                                        return <td key={cidx}> {col} </td>
                                    }
                                }
                            )}
                        </tr> 
                else return  <></>
               })
            }
            </tbody>
        </Table>
    );
}


// this other component where iam trying to map it

const MyTable = withAccordionRow(RenderTable);

  const [operatorData, setOperatorData] = useState({
        header: ["", "Nome", "Cognome", "Mail", "Telefono", "Ruolo", "Attivo"],
        data: [
            ['', '', '', '', 'Admin'],
 ['', '', '', '', 'Admin'], 
['', '', '', '', 'Admin'], 
['', '', '', '', 'Admin'],
           
        ]
    });


<MyTable className="table-borderless"
                                 header={operatorData.header}
                                 data={operatorData.data.map((item, index) => ([

                                     ...item,

                                     <ToggleOnIcon key={index}  showIcon={showToggleon} setShowIcon={setShowToggleon} onClick={()=>handleToggleOnIcon()}/>
                                 ]))}
                                 toggleIcon={showSquareIcon ? PlusSquare : DashSquare}
                                 linkArray={[{name: 'Modifica', to: '#'}, {name: 'Elimina', to: '#'}]}
                                 colspan={6}
                        />
// and even the toggle icon iam able to show only one at a time, can i get some suggetions , why iam unable to render it and what could be possible way to do it  

here i am not able to render the icon , but outside the mapping it works usually like it works perfetly , i tried with different options as well

How to publish updates using “eas update” when the build was created locally

So, these are the steps of my actions –

  1. Created app build locally using “eas build -p ios –clear-cache –local”.
  2. Uploaded the ipa file on App Store Connect using Transporter app.
  3. Made the app live on App Store.

Now, I have made some changes in the app and need to publish that change, for this I used “eas update” but didn’t get any OTA on the live app. I did some research and figured out that builds are supposed to be created on expo servers, only then will they receive OTAs.
The thing is my ios build has been failing on the cloud due to a common fastlane error which I am unable to resolve yet and have been struggling on it for long. Although, the builds have been successful locally.

My app is running on “expo”: “~46.0.19”.

Question
Is there a way I can send OTA updates on apps that were built locally and not on expo servers?

how to include bootstrap.bundle.min.js script in azure ad b2c

I have added the script of bootstrap.bundle.min.js for the carousel but the indicators are not automatically working moving from one to another indicator. version of bootstrap I am using is V5.
I have provided the cshtml file to loadURI in custom policy.

I have added the script of bootstrap.bundle.min.js for the carousel but the indicators are not automatically working moving from one to another indicator. version of bootstrap I am using is V5.
I have provided the cshtml file to loadURI in custom policy.

I am expecting for carousel to work automatically to move slide at certain intervals.

How to add image through props in React JS

I’m trying to create reusable card component and I don’t know how to add the image through the props, I would appreciate your help. Now I’m using {require(“../assets/wheat.svg”)} but it doesn’t work.

CardsScreen.js

import React from "react";

import styles from "../styles/card-styles/cards.css";

import Bounce from "react-reveal/Bounce";

const CardsScreen = () => {
  function Card(props) {
    return (
      <div className="card-content">
        <img className="card-image" src={props.view}></img>
        <h6 className="card-header">{props.heading}</h6>
        <p className="card-paragraph">{props.description}</p>
      </div>
    );
  }

  return (
    <div className="cards-container">
      <Bounce bottom>
        <Card
          view={require("../assets/wheat.svg")}
          heading="Heading"
          description="Lorem ipsum dolor sit amet consectetur. Nunc donec ullamcorper viverra lectus quis pretium volutpat eget. Aliquam ultrices tincidunt nulla commodo."
        />
      </Bounce>
    </div>
  );
};

export default CardsScreen;

Dataform – getting os username

How would I get the name of the user currently logged into the system using Dataform?
I tried this:

const os = require("os"); 
console.log(os.userInfo().username); 

but after typing “dataform compile” in the terminal I get this
enter image description here

Do you have any ideas? Thank you in advance

Returning a promise on a click event with Vanilla Javascript [closed]

I am new to Javascript and trying to resolve a Promise issue.

I have set up a function X(p1) with 1 parameter which returns a promise.

function X works successfully.

I also have function on a click event that then calls function X(value1) but this function seems to be asynchronous and not waiting for function X to resolve the answer?

I need function X to wait for the result so that I can then call printResults(results)

    function EventListener(event) {
    let value1 = event.target.value
    let newP = new Promise((resolve) => {
        const results = function X(value1)
        if (results.length !== 0) {
            resolve(results)
        } else {
            console.log("Warning ")
        }
    })
    newP.then(() => {
        printResults(results)
    })
}