Call function when user close browser/tab [duplicate]

I’m trying to call a function when the user closes the browser or tab, but it doesn’t work. I tried using unload, beforeunload, onbeforeunload, etc.. but nothing. Would anyone know any way to proceed?

this is the function I want to call:

populaTempoVisualizacao = () => {
    let tempoVisualizacao = formatTime(minutes) + formatTime(seconds) + formatMilliSeconds(milliseconds)
    const produtoId = idProduto
    const data = {
        tempoVisualizacao: parseInt(tempoVisualizacao),
        produtoId: produtoId,
    }

    fetch(urlSetTempoNaPagina, {
        method: "POST",
        mode: 'cors',
        cache: 'default',
        body: JSON.stringify(data),
        headers: {"Content-type": "application/json; charset=UTF-8"}
    })
}

and I tried the following way:

window.addEventListener('unload', function(event) {
    populaTempoVisualizacao()
})

or

window.addEventListener("beforeunload", () => {
    populaTempoVisualizacao()
})

Testing a function which is wrapped inside a setTime out function

I am having some issues testing a function which is wrapped inside a setTimeout function.
Basically, what I want to test is the setUpdate method gets called with a false parameter.

const UpdateContainer: FunctionComponent<UpdateProps> = ({
  showUpdate,
  showError,
  dateOfBirth,
}) => {
  
  const [isEditable, setIsEditable] = useState<boolean>(true);
  const [isEditing, setIsEditing] = useState<boolean>(true);
 

  


  const onCancel = function async() {
    setIsEditable(false);
    setIsEditing(false);
    setTimeout(()=> {
     ** /*Wants to check if this method is invoked with a false param*/**
      showUpdate(false);
    },600);
  };

  const initialValues: UpdateValues = {
    birth_date: dateOfBirth,
  };

  const formik = useFormik({
    initialValues: initialValues,
    
  });

  return (
    <Card
      cancelText={t('cancel')}
      confirmText={t('confirm')}
      isEditable={isEditable}
      isEditing={isEditing}
      setIsEditable={setIsEditable}
      setIsEditing={setIsEditing}
      onCancel={() => onCancel()}
    >
     
     
      <CardItem
        body={
          <Input
            disabled
            id="dateOfBirthUpdate"
            textTransform="none"
            type="text"
            value={moment(new Date(formik.values.birth_date ? formik.values.birth_date : '')).format('ll')}
          />
        }
      />
    </Card>
  );
};

export default Card;

I have tried following the jest docs, but for some reason the test is unable to detect the invoke of setUpdate function

This is what I have tried so far


``
  it('on Clicking Cancel inside a tool tip it sets the show update to false', async () => {
    tree(props)
    jest.useFakeTimers()
    act(()=>{
      jest.runAllTimers()
    })
    const cancelButton = screen.getByText('common:cancel');
    expect(cancelButton).not.toBeNull();
    userEvent.click(cancelButton);
    const toolTipCancel= screen.getByText('common:cancelEditTooltip.cancelButtonText')
    userEvent.click(toolTipCancel);
    await expect(props.showUpdate).toBeCalledWith(false)  
  });

`

`

How to generate git diff from text in js

I want to show difference between two text using diff2html and need git like unified diff for the same.
Is there any way( some CDN or library ) that can give me git diff between two texts.

I am not using node or anything its a simple web page.
So I want something that has CDN support.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Diff checker</title>
    <script type="text/javascript" src="diff-match-patch.js"></script>
    <!-- CSS -->
    <link rel="stylesheet" type="text/css"
        href="https://cdn.jsdelivr.net/npm/diff2html/bundles/css/diff2html.min.css" />

    <!-- Javascripts -->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/diff2html/bundles/js/diff2html.min.js"></script>
</head>

<body>

    <div id="main-elem"></div>


    <script>

        var diffHtml = Diff2Html.html( `--- Original
+++ New
@@ -1 +1 @@
-hello
+jello
` , {
            // drawFileList: true,
            matching: 'chars',
            outputFormat: 'side-by-side',
        });

        document.getElementById('main-elem').innerHTML = diffHtml;
        console.log(diffHtml);
    </script>
</body>

</html>

I want --- Original +++ New @@ -1 +1 @@ -hello +jello to be generated by the difference between two text

is it possible to use cssgrid as an interactive table?

Quick question. I have an idea that I am trying to implement. I have 6 columns and 19 rows. I want each column to have a different header inside of them (for instance? – column 1 has a header of Breakfast, column two has a header of Lunch..and so on) – the ROWS: I need time frame (5:00, 5:30, 6:00 ect)
to run down the left side of the grid. what I am HOPING to do with this is book reservations using the cssgrid as an interactive table. Meaning..the user can log in to the site, select a cell within the grid and then enter his/her name directly into the cell. Can someone tell me if this is possible and if you can point me in the right direction where I can get some tips to achieve this I would be grateful! My idea of cssgrid is to place an all white 3 field form inside of each cell in the grid, so that when they click on the cell – they only have to enter their info and hit submit..this data will then hold in the cell…any ideas?

I have looked a bit but am having trouble on how to static the column headers and the row times.

I created a Babylon with meshes loaded in a X Django app template, now I need to rotate it by clicking buttons located a dash-board on a y Django app

I’m using a Babylon in a Django project, created a app template that I have few meshes loaded and I did set buttons to rotate the meshes using addEventListener, it are working well when the UI buttons is located in the same HTML template where the canvas is loaded, APP X. My main goal is to have the UI buttons located in a template that will be a dash-board created on a different APP, APP Y on my Django project.
When I place the UI buttons in the Y APP (dash-board template) I get the error:
Uncaught TypeError:
Cannot read properties of undefined (reading ‘trackUbosInFrame‘)
at new e (uniformBuffer.ts:256:36)
at t.createSceneUniformBuffer (scene.ts:2405:26)
at Ar.createSceneUniformBuffer (engine.multiview.ts:203:12)
at t._createUbo (scene.ts:1933:41)
at new t (scene.ts:1690:14)
at HTMLDocument. (jackpot.js?v=:7:17).

My JS rotation setup located in my Django JS file inside X APP:

javascript 
  function createRotationLogic(mesh, axis, speed) {
            var rotationAxis;
            switch (axis) {
                case "X":
                    rotationAxis = BABYLON.Axis.X;
                    break;
                case "Y":
                    rotationAxis = BABYLON.Axis.Y;
                    break;
                case "Z":
                    rotationAxis = BABYLON.Axis.Z;
                    break;
                default:
                    rotationAxis = BABYLON.Axis.Y;
            }
        
            return function () {
                scene.unregisterBeforeRender(mesh);
                scene.registerBeforeRender(function () {
                    mesh.rotate(rotationAxis, speed, BABYLON.Space.LOCAL);
                });
                setTimeout(function () {
                    scene.unregisterBeforeRender(mesh);
                }, 30000); // Stop after 30 seconds
            };
        }
        
        // Function to set up rotation for a specific sphere
        function setupRotationForSphere(sphereIndex) {
            return function () {
                var speedInput = document.getElementById(`speedInput${sphereIndex}`);
                var axisDropdown = document.getElementById(`axisDropdown${sphereIndex}`);
        
                if (speedInput && axisDropdown) {
                    var speed = parseFloat(speedInput.value) || 0.01;
                    var selectedAxis = axisDropdown.value;
                    var rotationMesh = loadedMeshes[sphereIndex];
        
                    scene.unregisterBeforeRender(rotationMesh); // Unregister previous rotations
                    scene.executeWhenReady(function () {
                        scene.registerBeforeRender(createRotationLogic(rotationMesh, selectedAxis, speed));
                    });
                } else {
                    console.log("Speed input or axis dropdown null.")
                }
            };
        }
       
       // Usage for Sphere
       var rotateButton1 = document.getElementById("rotateButton1");
       if (rotateButton1) {
           rotateButton1.addEventListener("click", setupRotationForSphere(sphereIndex));
       } else {
           console.log("Rotate button 1 is null.");

     // Button to start rotation for 30 seconds
            function createRotationButtonListener(meshIndex) {
                  return function () {
                      
                      var speedInput = document.getElementById(`speedInput${meshIndex}`);
                      var axisDropdown = document.getElementById(`axisDropdown${meshIndex}`);
                      var speedButton = document.getElementById(`speedButton${meshIndex}`);
                      if (speedInput && axisDropdown && speedButton) {
                        speedButton.addEventListener("click", function () {
                            var speed = parseFloat(speedInput.value);
                            if (!isNaN(speed)) {
                                scene.unregisterBeforeRender(loadedMeshes[meshIndex]);  
                                scene.registerBeforeRender(function () {
                                    loadedMeshes[meshIndex].rotate(BABYLON.Axis.Y, speed, BABYLON.Space.LOCAL);
                                });
                            }
                        });
                        
                        axisDropdown.addEventListener("change", function () {
                            var selectedAxis = axisDropdown.options[axisDropdown.selectedIndex].value;
                            scene.unregisterBeforeRender(loadedMeshes[meshIndex]);
                            scene.registerBeforeRender(function () {
                                loadedMeshes[meshIndex].rotate(BABYLON.Axis[selectedAxis], 0.01, BABYLON.Space.LOCAL);
                            });
                        });
                    } else {
                        console.log("Speed input, axis dropdown, or speed button is null.");
                    }
                };
            }
              
              
              // Usage for Sphere
        var rotateButton1Listener = createRotationButtonListener(sphereIndex);
        if (rotateButton1 && rotateButton1Listener) {
            rotateButton1.addEventListener("click", rotateButton1Listener);
        } else {
            console.log("Rotate button 1 or listener is null.");

My UI elements located inside dashboard template inside the APP Y:

HTML
 <div id="rotateButton1">
        <button id="rotateButton1">Rotate for 30s</button>
        <label for="speedInput1">Rotation Speed:</label>
        <input type="number" id="speedInput1" step="0.1" value="0.1">
        <button id="speedButton1">Apply Speed</button>
        <label for="axisDropdown1">Rotation Axis:</label>
        <select id="axisDropdown1">
            <option value="X">X</option>
            <option value="Y" selected>Y</option>
            <option value="Z">Z</option>
        </select>
      </div>

I’ve tried to change the js code to the Y APP where the UI elements are located

Run the cypress test in incognito mode

i trying to configure github action, and i need to run the cypress test in incognito mode when I run it through a command in the terminal.

I try npx cypress run --spec "path/to/your/test-file.js" --browser chrome --config chromeWebSecurity=false, i try add this code in cypress config:

e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
      on('before:browser:launch', (browser = {},launchOptions) => {
        if (browser.family === 'chrome' && browser.name !== 'electron')
        launchOptions.args.push("--incognito");
        return launchOptions
      })
    }

But this helps me only when i run in with UI.

I also try npx cypress run --incognito "Path" , but it end with error: unknown option: --incognito

None of these options helped me run my test in incognito mode via a terminal command.

Angular ng build –prod outputhashing, My own names

When we use the ng build –prod command and have outputhashing set to “all”, we get output files with a hash, e.g. main.dse2324dacx3423.js. However, how to add your own text after main.myOwnText.js

During the ng build –prod command, I want it to get versions from my package.json
{ "name": "app-name", "version": "24.02.01", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" },

So how can I make the files generate the way I want?

I want the application to generate files with the name of my version that it downloads from package.json
main.24.02.01.js etc..

Change the color of a whole line in Dygraph

unfortunately I can’t provide code because of security reasons but I will ask my question nonetheless.
I wanted to know if it is possible to change the color of a whole point connection line in dygraphs (js package for plotting data).
I already found this post here on stack: dygraph-change-line-color, but this only covers the color changing of circular points on a line and not the line itself.

Even online the topic isn’t discussed explicitly and the official documentation doesn’t mention this either.

I already searched only and looked through the official documentation but as I mentioned above, I couldn’t find anything that covers my question even closely.

Dynamic import with GatsbyJS

  • we have a large GatsbyJS 3 (React) project which is used to build multiple websites.
  • The websites are build each with a specific environment file and then uploaded to different locations.
  • The websites have the same code base with a few exceptions (eg. website specific components and images).
  • We don’t use SSR.

The problem is that the website specific components are quite large and therefore bloat up the code of the individual websites which dont use those specific components. This results for example in a bad lighthouse score (unused code) and bad user experience (longer loading times).

Here is a strongly simplified example component which displays a website specific svg (loaded via gatsby-plugin-react-svg):

import React from "react";

import Site1 from "../../images/site1.svg";
import Site2 from "../../images/site2.svg";
import Default from "../../images/default.svg";

const Image = () => {
  let staticImage = <Default />;

  switch (process.env.GATSBY_SITE) {
    case "site1":
      staticImage = <Site1 />;
      break;
    case "site2":
      staticImage = <Site2 />;
      break;
    default:
  }

  return (
    <>{staticImage}</>
  );
};

export default Image;

I guess/understand this wont work because GatsbyJS/React/Webpack (?) simply does not know what happens in this component and when to show which image.

I tried to use loadable components to address this issue but had no success. This is the example code from above but with loadable components:

import React from "react";

import loadable from "@loadable/component";

const DynamicImage = loadable(async () => {
  switch (process.env.GATSBY_SITE) {
    case "site1":
      return import("../../images/site1.svg");
    case "site2":
      return import("../../images/site2.svg");
    default:
      return import("../../images/default.svg");
  }
});

const Image = () => {
  return <DynamicImage />;
};

export default Image;

With this code all three images are still loaded although only one is shown. I would expect that only the used/required image (or component in other cases) is loaded.

Design split in the middle when placed on mobile screens [closed]

I’m working on an internship project and I’m doing the front. It’s “cutting” in the middle when I put it on mobile screens, as you can see… can anyone help me with this, I’ll be grateful!
https://lumomag.github.io/porto-sfs/

Here is the website. I also accept suggestions 🙂

I tried to adjust the width of the body or see if there was any overflow, but I didn’t find a solution.

How can I change div content with JavaScript? No pop up, just Vanilla JavaScript

I have a div which is going to contain a simple memory card game. The first thing the user is going to see will be a couple of buttons: one for the instructions and another one to start the game.
I would like to make everything happen inside this div, without using popup windows and only using Vanilla JavaScript (even because I am a beginner), so when the user clicks on “instructions” for example the button disappears and the instructions appear (always inside the div), with a “back to menu” button inside. Then, when the user clicks on “start new game”, the game starts inside the div

I have found this idea but there is a pop up which I don’t want it to happen, and the div where the initial message and the game happen have different dimensions. I want them to have the same dimensions (obviously they will change because of responsiveness, but this is another thing). I can add my HTML code done so far, but of course is incomplete and makes no sense

<body>
  <!-- Audio files for both win and game over with hide class -->
  <audio id="win-rick" class="hide" controls>
        <source src="assets/audio/you-winnn.mp3" type="audio/mpeg" />
        Your browser does not support the audio element.
    </audio>
  <audio id="lose-rick" class="hide" controls>
        <source src="assets/audio/game-overrr.mp3" type="audio/mpeg" />
        Your browser does not support the audio element.
    </audio>

  <!-- Main heading -->
  <h1 class="heading">Memento Amiga</h1>

  <!-- Game container -->
  <div id="memory-game">

    <!-- Instructions / Start new game -->
    <div id="magicDiv">
      <button id="instrBtn" type="button">How to play</button>
      <button id="startBtn" type="button">Start new game</button>
    </div>
  </div>
  <div id="click-numbers">
    <p id="click-counter-p">Click counter: <span id="click-counter-n">0</span></p>
    <p id="timer-id">Timer: <span id="real-time">60</span></p>
  </div>
  <script src="assets/js/script.js"></script>
</body>

How can I create a genre drop down list using javascript?

I have displayed a list of films from an array fetched from an API and I need to filter the films into genres and create a dropdown list of genres. I can’t for the life of me figure out how to do it, can anyone please help?

Each item in the array already has a genre assigned to it, so could be accessed by film.genre…

const squareEyesData = async(url) => {
  try{
   let response = await fetch(url)
   let films = await response.json()
    localStorage.setItem("listOfFilms", JSON.stringify(films.data))
  } catch(error){
    console.error("unable to fetch:" + error);
  }
}

squareEyesData(squareEyesAPI)

let films = JSON.parse(localStorage.getItem("listOfFilms"))

console.log(films);



function createFilmsHtml(film){
const filmBox = document.createElement('div');
  filmBox.classList.add('film-box');

const filmContent = document.createElement('div');
filmContent.classList.add('film-content');

const filmHeader = document.createElement('h3');
filmHeader.textContent = film.title; 

const filmPoster = document.createElement('img');
filmPoster.src = film.image.url;

const filmPriceBox = document.createElement('div');

const filmPrice = document.createElement('div');
filmPrice.textContent = film.price + "NOK";

filmBox.appendChild(filmContent);

filmContent.append(filmHeader, filmPoster, filmPriceBox);

filmPriceBox.append(filmPrice);

return filmBox;
}


function showFilms(films){
const filmDisplayBox = document.getElementById('films-display-box');
films.forEach((film) => {
const filmHtml= createFilmsHtml(film);
filmDisplayBox.appendChild(filmHtml);
});
}

showFilms(films);

swiper.js Navigation and Pagination – wrong position (middle and bottom of site)

I just got started using swiper.js and so far it goes pretty well.

There’s only one problem: the pagination bullets and navigation arrows are not positioned correctly.

The arrows are in the middle of the page and the pagination bullets on the bottom of the page (not of the slider container).

I’m sure it’s just a little thing that I oversee here (maybe an additional container around the swiper?) – could somebody please help me out here? Thanks!

Here’s the HTML section with the slider:

<section class="mex-card">
    <div class="swiper swiper-chocolate-qui-gon-jinn-749">
        <div class="swiper-wrapper">
          <div class="swiper-slide swiper-slide-ff36">
            <div
              class="swiper-slide-content swiper-carousel-animate-opacity swiper-slide-content-dd9d"
            >
              <div class="swiper-slide-text swiper-slide-text-c0a7">FREE</div>
      
              <div class="swiper-slide-text swiper-slide-text-906b">Free plan</div>
            </div>
          </div>
      
          <div class="swiper-slide swiper-slide-ff36">
            <div
              class="swiper-slide-content swiper-carousel-animate-opacity swiper-slide-content-dd9d"
            >
              <div class="swiper-slide-text swiper-slide-text-f04a">$10</div>
      
              <div class="swiper-slide-text swiper-slide-text-e016">$10 plan</div>
            </div>
          </div>
      
          <div class="swiper-slide swiper-slide-ff36">
            <div
              class="swiper-slide-content swiper-carousel-animate-opacity swiper-slide-content-dd9d"
            >
              <div class="swiper-slide-text swiper-slide-text-f04a">$20</div>
      
              <div class="swiper-slide-text swiper-slide-text-e016">$20 plan</div>
            </div>
          </div>
      
          <div class="swiper-slide swiper-slide-ff36">
            <div
              class="swiper-slide-content swiper-carousel-animate-opacity swiper-slide-content-dd9d"
            >
              <div class="swiper-slide-text swiper-slide-text-f04a">$30</div>
      
              <div class="swiper-slide-text swiper-slide-text-e016">$30 plan</div>
            </div>
          </div>
      
          <div class="swiper-slide swiper-slide-ff36">
            <div
              class="swiper-slide-content swiper-carousel-animate-opacity swiper-slide-content-dd9d"
            >
              <div class="swiper-slide-text swiper-slide-text-f04a">$30</div>
      
              <div class="swiper-slide-text swiper-slide-text-e016">$30 plan</div>
            </div>
          </div>
        </div>
      </div>
      <div class="swiper-button-prev"></div>
      <div class="swiper-button-next"></div>
      <div class="swiper-pagination"></div>
      
     
    
</section>

CSS:

.mex-card {
    box-sizing: border-box;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    margin-bottom: 0.75rem;
    border: 1px solid #dcdfe2;
    border-radius: 0.1875rem;
    background-color: #ffffff;
}

/* https://studio.swiperjs.com */
@import url(https://cdn.jsdelivr.net/npm/swiper@11/swiper.min.css);@import url(https://cdn.jsdelivr.net/npm/swiper@11/modules/a11y.min.css);@import url(https://cdn.jsdelivr.net/npm/swiper@11/modules/navigation.min.css);@import url(https://cdn.jsdelivr.net/npm/swiper@11/modules/pagination.min.css);.swiper-carousel{position:relative;margin:0 auto;max-width:100%;overflow:hidden}.swiper-carousel .swiper-slide,.swiper-carousel swiper-slide{position:relative}:root {--swiper-navigation-color: rgba(191, 191, 191, 1);--swiper-pagination-color: rgba(191, 191, 191, 1);--swiper-pagination-bullet-inactive-color: rgba(191, 191, 191, 1);}.swiper-chocolate-qui-gon-jinn-749 {user-select: none;box-sizing: border-box;overflow: hidden;width: 100%;height: auto;padding: 20px 0px;}.swiper-chocolate-qui-gon-jinn-749 .swiper-slide {display: flex;align-items: center;justify-content: center;width: 100%;height: 100%;position: relative;box-sizing: border-box;}.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-content {width: 100%;height: 100%;display: flex;position: relative;z-index: 1;box-sizing: border-box;}.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-ff36 { background-color: rgba(255, 255, 255, 1);border-radius: 16px;border: 1px solid rgba(189, 189, 189, 1); }.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-content-dd9d { align-items: flex-start; justify-content: flex-start;flex-direction: column;padding: 48px 32px;gap: 16px; }.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-text-c0a7 { color: rgba(140, 140, 140, 1);text-align: left;font-size: 24px;line-height: 1.5;font-weight: bold; }.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-text-906b { color: rgba(155, 155, 155, 1);text-align: left;font-size: 14px;line-height: 1.5; }.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-text-f04a { color: rgba(181, 255, 0, 1);text-align: left;font-size: 24px;line-height: 1.5;font-weight: bold; }.swiper-chocolate-qui-gon-jinn-749 .swiper-slide-text-e016 { color: rgba(181, 255, 0, 1);text-align: left;font-size: 14px;line-height: 1.5; }