I can’t creat HTML Web Workers API

I am studying about HTML via w3schools.com.
I have built all examples and tests, questions.
But only one thing has troubled to me.
This is just HTML Web Workers API.
The main HTML code is here.

https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webworker

And the main start worker function is:

function startWorker() {
  if (typeof(Worker) !== "undefined") {
    if (typeof(w) == "undefined") {
      w = new Worker("demo_workers.js");
    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
  }
}

In this function, the code created new Worker named “demo_workers.js”.
“demo_workers.js” is in https://www.w3schools.com/html/html5_webworkers.asp

In detail…

var i = 0;
function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()",500);
}
timedCount();

Of course the online compiler runs well, but I have created the same HTML and JavaScript code, but it did not run.
I want to know why this has happened.

javascript works only for the first element

I’m using JS code to recieve pick up and drop off locations in a form through google maps api.

However the code only works for the first element (pick up location).

I can not define them as classes because these elements are classed in a different class due to style issues.
I also tried to create two different IDs and functions. but that did not work as well.

 <div class="row">
    <div class="col-md-6">
            <div class="form-group">
                <span class="form-label">Pickup Location</span>
                <input id="searchTextField"class="form-control" type="text" placeholder="Address">
            </div>
    </div>
    <div class="col-md-6">
            <div class="form-group">
                <span class="form-label">Drop off Location</span>
                <input id="searchTextField" class="form-control" type="text" placeholder="Address">
            </div>
    </div>
</div>

and js code is:

 function initialize() {
     var input = document.getElementById('searchTextField');
     new google.maps.places.Autocomplete(input);
 }
 
 google.maps.event.addDomListener(window, 'load', initialize);
 

    

Javascript: Recursive function with promise and resolve when count is reached

I am stuck trying to build a recursive function that is already defined as a promise.
I have not been able to apply the recursive pattern on the code below – what I am missing?

Requirement: receivingMessages must be a promise.

let globalMessageArray = [];

// loopFor is the number of loop receivingMessages must loop for 
// until it reached 1 to return globalMessageArray which is the accumulator

function receivingMessages(params, loopFor, globalMessageArray) {
    return new Promise((resolve, reject) => {
        const command = new ReceiveMessageCommand(params);
        client.send(command).then(
            (data) => {
                if (data && data.Messages && data.Messages.length) {
                    data.Messages.forEach(msg => {
                        globalMessageArray.push(msg);
                    });
                };
                return resolve(globalMessageArray);
            },
            (error) => {
                return reject(error);
            }).then(
            (globalMessageArray) => {
                if (loopFor = 1) {
                    return resolve(globalMessageArray);
                } else {
                    return resolve(receivingMessages(params, loopFor - 1, globalMessageArray));
                };
            });

    });
};

Getting Triple quotes in javascript

Android mobile app is sending the body in a API of Nodejs with the request data as

{ 
    "openingHour":['"02:00PM"','"03:00PM"']
}

and in the backend system I am unable to remove either single quote or double quote using JS only.

my requirement is

{ 
    "openingHour":["02:00PM","03:00PM"]
}

OR 

{ 
    "openingHour":['02:00PM','03:00PM']
}

how can i achieve the above requirements.

How do I change the contents of a css element after a :hover pseudo-element activates using javascript?

I currently have 2 boxes, one box that is red, and when my mouse hover overs it the box turns red. The other box is blue, and when my mouse hovers over the box it turns blue.

What I want to have happen is that when my mouse hovers over box 1 the box turns blue AND box 2 turns red. (Same idea with Box 2 but switch the colors

Here is the code that I tried already, I know that the issue is with the javascript but I don’t understand why the javascript isn’t working

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">
<<head>
<body>
    <div class='parent'>
      <div class="outlineOne"></div>
      <div class="outlineTwo"></div>
    </div>
</body>

CSS

body {
  background: #2F2F2F
}
.outlineOne, .outlineTwo {
  display: inline-block;
  background: #2F2F2F;
  width: 100px;
  height: 100px;
  border: 2px solid black;
  margin: 20px 20px;
}
.outlineTwo {
  background: blue;
}
.outlineOne {
  background: red;
}
.outlineOne:hover{
  background: blue;
}
.outlineTwo:hover {
  background: red;
}

Javascript

const outlineOne = document.querySelector('.outlineOne');
const outlineOneHover = window.getComputedStyle(outlineOne, ':hover');
const outlineTwo = document.getElementsByClassName('outlineTwo')
if (outlineOneHover.style.background = blue) {
  outlineTwo[0].style.backgroundColor = 'red';
};

Clickable Chart.js chart title

In version 2.x of Chart.js I could register an onClick on options and get clicks that were done on the chart title. As expected based on this from the 3.x Migration Guide:

options.onClick is now limited to the chart area

this now no longer works. To show this, see below.

Version 2.x:

var chart = new Chart(document.getElementById('chart').getContext('2d'), {
    type: 'bar',
    data: {
        labels: ['Apples'],
        datasets: [{
            label: 'Fruit',
            backgroundColor: 'hotpink',
            data: [11],
        }]
    },
    options: {
        title: {
            display: true,
            fontSize: 24,
            text: "CLICK ME! (Or the chart itself)",
        },
        onClick: function(area){
            const title = this.titleBlock;
            const hitTitle = !!title
                && area.offsetX > title.left && area.offsetX < title.right
                && area.offsetY > title.top && area.offsetY < title.bottom;
            document.getElementById('log').innerHTML += hitTitle ? "Title click!!<br>" : "Generic chart click<br>";
        }
    },
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="chart"></canvas>
<div id="log"></div>

Version 4.x (does not even trigger onclick for title!):

var chart = new Chart(document.getElementById('chart').getContext('2d'), {
    type: 'bar',
    data: {
        labels: ['Apples'],
        datasets: [{
            label: 'Fruit',
            backgroundColor: 'teal',
            data: [11],
        }]
    },
    options: {
        plugins: {
          title: {
              display: true,
              font: { size: 24, },
              text: ["CLICKING ME IS OF NO USE!", "(Clicking the chart itself works)"],
          },
        },
        onClick: function(area){
            const title = this.titleBlock;
            const hitTitle = !!title
                && area.offsetX > title.left && area.offsetX < title.right
                && area.offsetY > title.top && area.offsetY < title.bottom;
            document.getElementById('log').innerHTML += hitTitle ? "Title click!!<br>" : "Generic chart click<br>";
        }
    },
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="chart"></canvas>
<div id="log"></div>

How can I handle onClick for Chart.js title (and subtitle) in v4 and above? Is it even possible?

i18next avoid retranslation of nested components

I am using i18next with React for my project. For most of the translations I use the t() function with normal text. However, for some cases I would prefer to use the <Trans /> component.

I prepared some example below:

function Example() {
    const { t } = useTranslation();

    const reusableComponent = <p>{t('TranslateMeOnlyOnce')}</p>;

    return (
        <>
            {reusableComponent}
            <Trans i18nKey={'OnlyOnceWrapper'}>
                The reusable component says {reusableComponent}
            </Trans>
        </>
    )
}

Which expect would my ranslation file to look something like this:

...
TranslateMeOnlyOnce: 'Translate me only once',
OnlyOnceWrapper: 'The reusable component says <1>Translate me only once</1>',
...

However, as you can see I would be required to translate the text of the nested component twice. I would really like to just translate the The reusable component says {reusableComponent} in the second translation string and not all of the first translation string for another time.

For those wondering why I would want to do this, lets say const reusableComponent is a Create Button with some function to create a new entry placed at the top of the Screen. When however, there is no entry displayed in my list of entries I want to display a message saying something like: ‘Unfortunately there is no entry yet. Click on [CreateButtonIsDisplayedHere] to create a new entry’.

Let’s say I experience that users find a translation ‘New’ instead of ‘Create’ more useful or the other way round, I would want to change only the translation of the button and not every other place containing this button.

I also found myself a solution to this issue already, however, in my experience this is super ugly to maintain as I need to pass the content as string and not as React child Element which pretty much take all advantages of using the <Trans /> Component and I could better use the t() function using sprintf.

function UglySolution() {
    const { t } = useTranslation();

    const reusableComponent = <p>{t('Translate me only Once')}</p>;

    return (
        <>
            {reusableComponent}
            <Trans 
                i18nKey={'OnlyOnceWrapper'} 
                components={[reusableComponent]} 
                variables={{ v: t('Translate me only Once') }} 
                defaults='The reusable component says <1>{{v}}</1>'
            />
        </>
    )
}

Which would expect my translation file to look something like this:

...
TranslateMeOnlyOnce: 'Translate me only once',
OnlyOnceWrapper: 'The reusable component says <1>{{v}}</1>',
...

So my question is: Can I make my translation to look something like the second example I created without using the ugly <Trans /> code from the second example and more something like in the first example I created?

How to hide the my source code in react.js?

I tried the following formulas to hide the codes of my project in Google Chrome and my codes are hidden, but when I close my project and open it again, the process returns to the beginning and my codes are not hidden.
How Can I Solve This?

scripts: {
      "build": "GENERATE_SOURCEMAP=false react-scripts build"
    }

and

env file:

GENERATE_SOURCEMAP=false 

Return full data on JavaScript Promise for a function within a class while using node-client-ntlm

I have a function within a class that makes a call and returns a promise object with data. I do get the data back the issue is I cannot figure out how to make the call wait till all of the data is returned at the moment it only returns a few lines of data and cuts off the rest of the return.

  async callCurl(postFields) {
    this.postFields = postFields;
    const response = await client
      .request(
        {
          url: this.url,
          method: "POST",
          debug: true,
          body: "folderGuid=" + this.postFields,
          headers: {
            "content-type": "application/x-www-form-urlencoded",
          },
          resolve: true,
        },
        "username",
        "password",
        "",
        "domain"
      )
      .then((response) => {
        console.log(response.body);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    //return response;
  }

How to pass js const as an argument to a php function [duplicate]

I have a JS code with a constant that gets input value from a form, and I need to pass this constant as an argument to a php function, but I don’t know how to format this code.

So far I’ve tried doing this, but it’s not working:

<script>
...
const companyId =  $hicSelector.select2('data')[0]['id'];
const p = <?php $model->getTableInfo(?> companyId <?php ); ?>;
...
</script>

Some details that may be useful: companyId returns an integer; the result from getTableInfo is an array (key => item), and I need to access each item from this array using the key.

Live update results from database wih every charachter the user types in the search bar

I want to live update a table f results based on the charachters the user type in the search-bar

This is my search.ejs

<div class="search">
    <form action="/search" method="post">
      <div class="form-floating mb-3">
        <input id="search-bar" type="text" class="form-control" id="name" placeholder="name" name="name" required>
        <label for="name">name</label>
      </div>
      <button type="submit" class="btn btn-primary btn-md">Search</button>
    </form>
  </div>
  <table class="table table-striped table-hover">
    <thead>
      <tr>
        <th scope="col">First name </th>
        <th scope="col">Last name</th>
        <th scope="col">Number</th>
        <th scope="col">Date</th>
      </tr>
    </thead>
    <tbody> 
      <% array.forEach(item => { %>       
        <th><%= item.firstname %> </th>
        <th><%= item.lastname %> </th>
        <th><%= item.number %> </th>
        <th><%= item.date %> </th>
      <% }) %>
    </tbody>
  </table> 

This is script.js to listen to keys typed in by the user

document.getElementById('search-bar').addEventListener('keyup', function() {
  const searchTerm = this.value;
  fetch(`/search?q=${searchTerm}`)
});

This is my server.js

app.get('/search', function(req, res) {
  var title = "";
  var body = "";
  var script = "";
  var classe= "";
  var style = "";
  const q = req.query.q;
  console.log(q);
  connection.query('SELECT * FROM STUDENT WHERE firstname LIKE ?',[q+"%"],function(err,data){
    if(err){
      console.log(err);
    }
    else{
      res.render('search',{style:style,classe:classe,array:data,modalTitle:title,modalBody:body,script});
    }
  });
});

Here I am querying my database for the name of students starting with the charachters typed by the user, when i log the data to the consol i get the response just like i want nad it’ updated with evey key stroke, but the the array sent to the template is empty so i don’t get in data to show on the table, i understand that the initial array is sent empty while rendering the page for the first time, but my question is how to render the array again to my template after getting the array from the database ?

I tried a lot but the array is always sent empty to the template

Is there a way to make a responsive grid?

I’m building a grid, and i don’t know how should i go about making the cells fill the space between them, when the grid size’s changes.

I have a function which create a grid, and it takes size as parameter.

What to add to grid-square class, so the cells take the whole space?

//get the grid div
const container = document.querySelector("#container");

function changeColor(e) {
  const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
  e.target.style.backgroundColor = "#" + hoverColor;
}

function createDivs(size) {
  //generate grid elements
  for (let i = 0; i < size * size; i++) {
    const newDiv = document.createElement("div");
    newDiv.classList.add("grid-square");
    newDiv.addEventListener("mouseover", changeColor);
    container.appendChild(newDiv);
  }
}

createDivs(2);
* {
  box-sizing: border-box;
}
#container {
  display: flex;
  background-color: rgba(49, 49, 49, 0.281);
  width: 50vw;
  height: 50vh;
  flex-wrap: wrap;
}

.grid-square {
  background-color: white;

  width: 50%;
  aspect-ratio: 1/1;
}

.grid-square:hover {
  cursor: pointer;
}
<!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" />
    <title>Etch a Sketck</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

What is the purpose of WindowProxy?

Background

The HTML spec introduces the concept of the WindowProxy.

It says:

A WindowProxy is an exotic object that wraps a Window ordinary object,
indirecting most operations through to the wrapped object. Each
browsing context has an associated WindowProxy object. When the
browsing context is navigated, the Window object wrapped by the
browsing context’s associated WindowProxy object is changed.

The WindowProxy platform object is created when the browsing context is created by the host, as defined in ECMAScript’s InitializeHostDefinedRealm (step 8). It is directly set to be the global this value.

At that same point, the Window object is created, set to be the global object.

Through the ECMAScript spec, we see that whenever a lookup of an identifier happens, it first searches the environment record of the current execution context, and if not found continues out all the way out to the Global Environment Record, which in turn looks for the identifier on the global object.

As far as I can see, this set of operations never uses the global this value.

Questions

  1. Are there any operations in ECMAScript that use the global this value? If so, which?
    Edit
  • This StackOverflow question answers the high-level purpose of WindowProxy. My question above is related the the spec and how exactly the operations delegate to the WindowProxy object, by virtue of it being the global this value.
  • Article with some interesting, but vague, information not related to the ECMAScript spec.

next dynamic routes 404 firebase hosting

Using next.js app deployed on firebase.

I have deployed the app already and using some time.

  1. I created a dynamic route page
  2. Deployed again app
  3. I could access the dynamic page via a router, but once I refresh the page I got a 404 page not found

Solutions that I tried and didn’t work:

  • Rewrites with dynamicLink true
  • Rewrites with destination to the dynamic route and regex / source
"rewrites": [
      {
        "source": "/job/**",
        "destination": "/job/[jobId]/index.html"
      }
  • cleanUrls true
  • trailingSlash: true plus rewrite config with destination to the dynamic page
  • Any many more

I found a ton of solutions for this problem but no one didn’t work for me.

Any idea?

firebase.json file:

{
  "hosting": {
    "public": "out",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "cleanUrls": true,
    "rewrites": [
      {
        "source": "**",
        "destination": "out/index.html"
      }
    ]
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ],
      "predeploy": ["npm --prefix "$RESOURCE_DIR" run build"]
    }
  ]
}

Using python to connect or write a google apps script to a google sheet

Is it true that it is not possible to directly connect a Google Apps Script (which uses JavaScript) to a Google Sheets spreadsheet using Python?

I am asking this more as a design question: would it not be possible to keep a Google Apps Script in a file and simply use Python to connect it to a gsheets spreadsheet using the spreadsheet id? I have not found a way to do this, but it would be interesting to hear if anyone has found a way to do it and if so how.