Is there any document event to detect specifically window close and send current data with postMessage?

Given the following code

window.addEventListener("visibilitychange", () => {
   // do something here
    if (iframe)
            iframe.contentWindow.postMessage({
              type: "visit_close",
              page: document.title,
              time: timeSpentOnPage,
              shop: key,
              user: member_id,
            });
}

Is there any other reliable way to check if window is closing. Problem with visibilitychange event is that it gets fired on both load and unload.

As far as I remember, unload event is not reliable.

Jank in CSS transform animation

I’m getting some jank/stutter in my animation in my React App. I have a simple carousel with infinite scroll. But I’m getting the jank when I look at the site on my phone and when I try to use .scss instead of css files. You can see the jank/stutter in the attached codepen. All of the css is in index.scss. HTML and javascript are in App.js. Please let me know if you need any more info, this has been driving me crazy.

https://codesandbox.io/s/codepen-with-react-forked-zq6lly?file=/src/components/App.js

Problems importing a p5.js library into a TypeScript project running a p5 Instance

I have recently been trying to switch from JavaScript to TypeScript, and just started a new p5.js project based on a p5.js TypeScript template

My project:

https://github.com/rsegrest/Nodes-and-Edges/tree/trying_to_import_p5.experience_library

The template I started with:

https://github.com/fal-works/p5js-template-petr-plus

Right now I am trying to see if I can use a couple of the libraries available on the p5.js website (under “Libraries”). The first I have been trying to import is called p5.experience, but I have been running into one problem after another getting it to work well with the rest of my project.

I have tried importing the p5.experience library as a script in my index.html file, and also directly inside the project. I don’t think there are any type definitions, so I am trying to bring it into my Typescript environment as Javascript, which seems to be causing a few problems.

I usually have to do a lot of configuration (and trial and error) on TypeScript projects, and have made some modifications to this template, including setting up Jest for unit testing. I had to work through configuring tsc and eslint for allowing JS file and TS files to exist side-by-side, but I believe I have that part of the puzzle worked out…(?)

However, I see that when the p5.experience.js file is loaded it is supposed to augment the functions available in p5, but it is choking on some functions like “stroke” that it may be assuming to be global.

Here is the project branch where I am trying to import the project, and the link points to the branch where I was trying and so far failing to import the library:

https://github.com/rsegrest/Nodes-and-Edges/tree/trying_to_import_p5.experience_library

Thanks for reading, and I would really appreciate any pointers or direction you all could give me, or just tell me what all I am doing wrong!

Easier way to display day.js in multiple locations?

I’m currently studying web development and I’m hoping one of you guys may help.

I’m currently coding the mandatory weather app that everyone and his dog has made lol.

My problem is that on the homepage I have 3 cards displaying with 3 different cities.
I want to display the current date underneath each city by using class=”date”.

But to do it in 3 instances on the same I’ve had to use date,date2 and date3. Which I’m thinking a for loop or something similar could easily fix rather than defining it 3 times.

Any help appreciated!
Thanks!

HTML

<section class="row">
            <h2>  Cities</h2>
            <section class="row">
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    London 
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date" class="date">date </span> <br/>
                      Temp:<span id="temp"></span> 
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    Birmingham
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date2" class="date">date </span> <br/>
                      Temp:<span id="temp"></span> 
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    Wolverhampton
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date3" class="date">date </span> <br/>
                      Temp:<span id="temp"></span> 
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
            </section>
          </div>
          <div class="col-xs-12 col-lg-3">
            <h2>Search</h2>
            <input class="Search col-12 border-radius pb-1" placeholder="Enter City" id="search">
            <ul class="list-group mb-2 pb-2">
                <li class="list-group-item">An item</li>
                <li class="list-group-item">A second item</li>
                <li class="list-group-item">A third item</li>
                <li class="list-group-item">A fourth item</li>
                <li class="list-group-item">And a fifth one</li>
              </ul>
          </div>
          <div class="col-xs-9 col-lg-9">
            <h2 class="subtitle">Results:</h2>
            <!--search results class="results-item"-->
          </div>
        </section>

JavaScript/JQuery

let nowDate = now.format('D / M / YY')
let date = $('#date')
let date2 = $('#date2')
let date3 = $('#date3')
date.text(nowDate);
date2.text(nowDate);
date3.text(nowDate);

Using JavaScript, how can I create an array with a specific width (number of columns)?

I have an array of columns that represents a row of data in a grid.

It looks something like the following:

let row = [rowId,'string value', 'string value 2', 'string value 3'];

I need to generate a dynamic row of data depending upon a variable number of columns the row will have. In other words, I need the array to be initialized so it contains the id and then X number of columns (depending upon the variable number of columns the grid will have).

[id, 'col-1', 'col-2', ...]

I currently have a ridiculous method which works and looks like the following:

getNewRow(maxKey: number, rowWidth: number){
    switch (rowWidth){
      case 1:{
        return [maxKey, 'col 1'];
        break;  
      }
      case 2:{
        return [maxKey, 'column 1', 'col 2'];
        break;  
      }
      case 3:{
        return [maxKey, 'column 1', 'col 2', 'col 3'];
        break;  
      }
      case 4:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4'];
        break;  
      }
      case 5:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5'];
        break;  
      }
      case 6:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6'];
        break;  
      }
      case 7:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7'];
        break;  
      }
      case 8:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8'];
        break;  
      }
      case 9:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8', 'col 9'];
        break;  
      }
      case 10:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8', 'col 9', 'col 10'];
        break;  
      }
    }

maxKey is just a simple way of insuring that the id column gets set to a new unique value.

My Questions

  • Is it possible to generate a row of data like this dynamically?
  • Is there some way to create a an array on the fly that has a dynamic width (based on the number of columns)?

How to assign a Singular Keys Array to Multiple Nested Value Arrays

I want to assign the keys in (arr1) to the strings in each nested array in (arr2).
I am only a month into learning javascript, and have been stuck on this problem and have been trying to find a working method.

Given the following arrays:

 arr1 = ["Date","Start","High","Low","End","AdjEnd","Amount"] //KEYS I WANT TO ASSIGN TO EACH STRING
 arr2 = [["1997-06-01","75","80","65","78","79","3000"],
         ["1997-06-02","70","75","60","73","74","3300"],
         ["1997-06-03","80","85","70","83","84","3800"],...] // THERE ARE 10,000+ OF THESE STRINGS

I want the output to create objects that look like this:

var newArray = [
{
  Date: "1997-06-01",
  Start: "75",
  High: "80",
  Low: "65",
  End: "78",
  AdjEnd: "79",
  Amount: "3000"
}

{
  Date: "1997-06-02",
  Start: "70",
  High: "75",
  Low: "60",
  End: "73",
  AdjEnd: "74",
  Amount: "3300"
}

{
  Date: "1997-06-03",
  Start: "80",
  High: "85",
  Low: "70",
  End: "83",
  AdjEnd: "84",
  Amount: "3800"
}

//continuing through all nested arrays

I can get the format I am looking for with this code, but it is not practical for thousands of arrays.

var result1 = {};
arr1.forEach((key, i) => result1[key] = arr2[0][i]);

var result2 = {};
arr1.forEach((key, i) => result2[key] = arr2[1][i]);


// result3 and so on

var allresult = [result1, result2] //add result3 and so on
console.log(allresult);

Fetching an url to an image from API results in a 302 error

I am making a website in which I load images and other data from an API that is owned by someone else. The data is received in json format.

The response looks a bit like this:

{
  ...
  "users": [
    {
      "name": "John Doe",
      "profile_image": "https://api.<url>/img/<id>",
      "date_created": "<date>",
      ...
    },
    ...
  ]
  ...
}

The issue I’m facing is that when I fetch these posts using JavaScript and want to use the profile_image as the src for an <img> tag, I sometimes (not always) get an response of 302 as supposed to the 200 I want, and the image won’t load as a result of that.

My JavaScript looks kinda like this (very simplified):

function fetchUsers() {
  return fetch(url)
    .then(response => response.json())
    .catch(error => console.log(error));
}

async function loadUsers() {
  let users = await fetchUsers()
  users.forEach(user => {
    userDiv.innerHTML += createUser(user);
  });
}

function createUser(user) {
  return `
    <div>
      <h3>${user.name}</h3>
      <img src="${user.profile_image}">
    </div>
  `;
}

When I follow the url I got from the API myself in the browser I get send to the image without any problems.

I suspect that it has to do with the fact that the image url seems to be linking to another API containing the images. I also noticed that in the DevTools console I see an error about Cross-Origin Read Blocking (CORB) blocking a cross-orign response.

Does anyone have experience with this problem and might be able to help?

Would be greatly appreciated!

regular expression in javascript

I’m trying to create regex for the following validation:

  1. 5 to 15 characters
  2. only letters and numbers allowed
  3. no numbers at the beginning or the end

/^[A-Za-z][A-Za-z0-9]([A-Za-z0-9]+)$/
this for the 2nd & 3rd validation

so how can I add 5 to 15 characters validation to this regexp
I tried to write it like that but it doesn’t work
/^[A-Za-z][A-Za-z0-9]([A-Za-z0-9]+){5,15}$/

How can I save the data fetched from an API in Node.js´ global variable?

function request2API(option){
    const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2
const request = new XMLHttpRequest();
request.open('GET',  urlStart + ChList[option].videosList + keyPrefix + key);
request.send();
request.onload = ()=> {
    if(request.status === 200){
        const response = JSON.parse(request.response);
        console.log(response) //At this point the Object respond exists
        return response;
    };
};
};

let indexChannel = inputFunction("n Pick an option ")
let fetchedData = request2API(indexChannel); //By this point it has died
console.log(fetchedData);

I’ve tried to assignt the fetched data to a variable as one would do in regular javascript for a browser but it’s not working.

How can i order data by specific String Field

i have the following get method

  FirebaseFirestore.instance.collection('comments').limit(5)
        .orderBy('commentDate',descending: true)
        .get(const GetOptions(source: Source.server)).then((value){
          //outputs
          today
          yestrday
          oldest
          oldest
          oldest
           
       });

in previous method i am sorting comments according to the latest .

one of the fields is commentOwnerId : Lx33AN0RwDEWzO7T3xQV.

Perhaps the owner of the comment is not the most recent , However, I want to show it as a priority over the rest of the documents .

  FirebaseFirestore.instance.collection('comments').limit(5)
        .orderBy('commentOwnerId ',descending: true) // here i am stack 
        .orderBy('commentDate',descending: true)
        .get(const GetOptions(source: Source.server)).then((value){
          //outputs
          myComment (yesterday)
          today
          oldest
          oldest
          oldest
           
       });

i notice if the commentOwnerId field is Boolean instead of string value so it work as expected
but of course i cannot use Boolean since i need to chick if it was == my id or no then descending it to true if it was mine .

How could i handle it ?

Regular Expression for each password strength cases and names with spaces JavaScript

Could you help with regex with following situation?

  1. If the string is only numbers, only lowercase char, only uppercase, or only symbols.
    This is how far I got.
/[0-9]|[a-z]|[A-Z]|[[email protected]#$%^&*)(+=._-]/
  1. If the string is a mixture of the two cases(either numbers, lowercase, uppercase, or symbols)

  2. If the string has at least one number, one lowercase, one uppercase, and one symbol.

/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[[email protected]$!%*?&]$/

This is not related to password,
4) but if you want regex for a string that is consisted of numbers and alphabets and can have space in the middle (not at the start nor the end)

/^[a-zds]+$/

I would like it if someone could help me with case 2 and confirm the rest.
Thanks.

How do I implement a Antlr4 parser that resolve ambiguity when both rules use “==”?

I know the title is not clear enough. Here is the details. I need to parse something like below:

Client->iFrame.Initialise() {
  res = Server.loadStaticResource()
  if (res.status == 404 || res.status == 503) {  <1>
     throw Error()
  }
}
== Initialisation done! ==                       <2>
Client->iFrame.load(data) {
   moreStatements()
}

It is a Java-like syntax, except that we support a Divider (shown as == Initialisation done! == in the example). Note that:

  1. both <1> and <2> uses ==.
  2. It is treated as a Divider only if it appears at the beginning of the line (after spaces removed).
  3. Any character can be used between the starting == and ending == except for changelines.
  4. There could be more = in the Divider component, such as === 3 equals ===.

How should I implement that?

What I have tried?

I was looking for a way to use lookahead in the Lexer, but could not find any good examples. I am currently limiting the content between starting == and ending == to ONE word only.

My implementation is here:

  1. The parser: https://github.com/ZenUml/core/blob/b84c9ca0a6d023c5e520bf83a225e4931db134fc/src/g4/sequenceParser.g4#L88-L89
  2. The lexer: https://github.com/ZenUml/core/blob/main/src/g4/sequenceLexer.g4

plain CSS to Keep the nav on top of the page

<!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" />

        <!-- To place the footer at the bottom of the page -->
        <style>
            html,
            body {
                height: 100%;
            }

            #root {
                min-height: 100%;
                display: flex;
                flex-direction: column;
            }

            header {
                position: absolute; /* To pull the header out of the document flow */
            }

            main {
                flex: 1;
            }
        </style>

        <title>Document</title>
    </head>
    <body>
        <div id="root">
            <header>
                <h1></h1>
                <nav></nav>
            </header>
            <main></main>
            <footer></footer>
        </div>
    </body>
</html>

Let’s say h1 and nav is placed within header tag and this would look like below:

enter image description here

What I want to achieve is keeping the nav tag on top of the page while the h1 tag is being scrolled as usual:

enter image description here

I’ve tried adding position: sticky; and top: 0;, but it doesn’t seem to be working as the nav tag is placed within the header tag.

Should I be using JavaScript to achieve this? or is it possible to solve with plain CSS only?