Use IntersectionObserver To Trigger Event AFTER Element Completely Passes Threshold

I have a few IntersectionObserver‘s set up. observer toggles new boxes to be made as the user scrolls down the page. lastBoxObserver loads new boxes as this continuous scrolling happens.

What I would like to do is change the color of a box once it leaves the threshold set in the first observer (observer – whose threshold is set to 1). So, once box 12 enters the viewport, it passes through the observer, and once it has completely passed outside of the threshold for this observer and box 13 enters the observer, box 12’s background changes from green to orange, perhaps.

Is there a way to make this happen? Maybe by adding an additional observer, or adding code to observer? Any help is greatly appreciated.

Codepen: https://codepen.io/jon424/pen/NWwReEJ

JavaScript

 const boxes = document.querySelectorAll(".box");
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle("show", entry.isIntersecting);
          if (entry.isIntersecting) observer.unobserve(entry.target);
        });
      },
      {
        threshold: 1,
      }
    );

    const lastBoxObserver = new IntersectionObserver((entries) => {
      const lastBox = entries[0];
      if (!lastBox.isIntersecting) return;
      loadNewBoxes();
      lastBoxObserver.unobserve(lastBox.target);
      lastBoxObserver.observe(document.querySelector(".box:last-child"));
    }, {});

    lastBoxObserver.observe(document.querySelector(".box:last-child"));

    boxes.forEach((box) => {
      observer.observe(box);
    });

    const boxContainer = document.querySelector(".container");

    function loadNewBoxes() {
      for (let i = 0; i < 1000; i++) {
        const box = document.createElement("div");
        box.textContent = `${i + 1}`;
        box.classList.add("box");
        observer.observe(box);
        boxContainer.appendChild(box);
      }
    }

HTML

   <div class="container">
      <div class="box">0</div>
    </div>

CSS

 .container {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      align-items: flex-start;
    }

    .box {
      background: green;
      color: white;
      font-size: 4rem;
      text-align: center;
      margin: auto;
      height: 100px;
      width: 100px;
      border: 1px solid black;
      border-radius: 0.25rem;
      padding: 0.5rem;
      transform: translateX(100px);
      opacity: 0;
      transition: 150ms;
    }

    .box.show {
      transform: translateX(0);
      opacity: 1;
    }

    .box.show.more {
      background-color: orange;
    }

Can’t get CORS to work with firebase function

I’ve been trying to deploy a function to send me an email via a click on my website, but I can’t get CORS to work, I’ve tried a lot, a LOT of things. The weirdest thing is that a lot of the time it works on the google cloud console test and on reqbin but the most i’ve been able to accomplish with my website is getting an error, somehow the mail gets through but with no content.

If you are wondering what kind of error I get, well I’ve basically done them all depending on what I’ve tried but the classic is :

Access to XMLHttpRequest at ‘https://us-central1-myproject.cloudfunctions.net/send_mail’ from origin ‘https://myproject.web.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Function:

const functions = require('firebase-functions');

const nodemailer = require("nodemailer");

exports.send_mail = functions.https.onRequest((req, res) => {

    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Headers', '*');
    res.set('Access-Control-Allow-Methods', 'GET, OPTIONS, POST');

    let data = req.body;

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '[email protected]',
            pass: 'apassword'
        }
    });

    const mailOptions = {
        from: '[email protected]',
        to: '[email protected], [email protected]',
        subject: data.subject,
        text: data.text
    };

    transporter.sendMail(mailOptions, function(error, info){
    if (error) {
        console.log(error);
        res.status(400).send('Échec');
    } else {
        console.log('Email sent: ' + info.res);
        res.status(200).send('Succès');
    }
    });
});

Client side:

function send_email() {

    let sujet = document.getElementById("sujet").value;
    let texte = document.getElementById("corps").value;

    if (texte == "" && sujet == ""){
        window.alert("Veuillez remplir les champs");
        return;
    }
    if (sujet == ""){
        window.alert("Veuillez remplir le champ "Sujet"");
        return;
    }
    if (texte == ""){
        window.alert("Veuillez remplir le champ "Message"");
        return;
    }

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "https://us-central1-portfolio-d230a.cloudfunctions.net/send_mail");

    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
           console.log(xhr.status);
           console.log(xhr.responseText);
        }   
    };

    let data = `{
    "subject": "",
    "text": ""
    }`;

    let json = JSON.parse(data);
    json.subject = sujet;
    json.text = texte;  

    xhr.send(json);
}

I have also tried the CORS middleware and express

Any help would be greatly appreciated, thanks.

Firebase Functions Read from Firestore Database fails without an error

I’m trying to read data from my Firestore database in my cloud functions.

My Database:

cases -> 1 -> (number) min: 1

My code in my function https.onCall( async (data, context):

if(!data.caseslot) {
        console.log("no caseslot");
        //throw exception
    }
    else{
        console.log(data.caseslot); //this logs me 1
        var db = admin.firestore();
        db.collection('cases').doc('${data.caseslot}').get().then(snapshot => {
            console.log(snapshot.data().min); //"TypeError: Cannot read properties of undefined (reading 'min')"
        }).catch(reason => {
            console.log(reason);
        });
    }

At this point, I don’t know what I’m doing wrong. I double checked my database…

Jquery UI click on link

I have some links within div. If users click any area in the div, it should do something. But it should do something else if users click on a link.

How could I find out if the click is on a link?
BTW, I cannot use onclick() function on the link.

<head>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

<div class="mydiv">
do something<br>
<a href = "#"> do other</a><br>
do something<br>
</div>

<script>

$(document).ready(function(){
$(".mydiv").click(function(){
var ahref = $(this).attr('href');
if(ahref == null){
alert("do something")
}else{
alert("do other");
}
  });
});
</script>
</body>
</html>

Passing props and functions to child component react

My code works until I try and pass props AND functions to my child component.

import React from 'react';
import './App.css';
  
  
export function Key(props, {newText, setNewText}) {

  const handleClick = () => {
    setNewText(newText + props.value);
  }

  return (
    <button onClick={handleClick}>{props.value}</button>
  );
}

export default Key;

If I remove the props from the export section the code works fine – unfortunately I need to access the data being passed.

Any help appreciated.

Google apps script, improting data from spreadsheet to another with indexing

Target Spreadsheet
Inventory Spreadsheet

Im trying to make an inventory spreadsheet for daily use, where you can write in the recounted quantity, and with a button press itt will import it to another spreadsheet, using the index function to find the correct row. I just started using apps script/java and for now I cant make it work, some help with the indexing part would be appriciated.

When are IndexedDB operations executed?

In the documentation to IndexedDB I find examples like this

// Let us open version 4 of our database
var DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened
// successfully, or not
DBOpenRequest.onerror = function(event) {
  note.innerHTML += '<li>Error loading database.</li>';
};

DBOpenRequest.onsuccess = function(event) {
  note.innerHTML += '<li>Database initialized.</li>';

  // store the result of opening the database in the db
  // variable. This is used a lot later on, for opening
  // transactions and suchlike.
  db = DBOpenRequest.result;
};

As far as I understand, this first creates a request object and then defines two callbacks. But it never calls any code to execute the request. Still it seems to execute it sometime.

I am especially interested in the details, as it seems to be complicated to run different transactions after each other as transactions seem to be asynchronous.

GET … /socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found) (with framework Phaser)

So I try to make a mini game with the phaser framework but I have a problem I have this error that appears “GET http://localhost:8081/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)” it’s been at least 3 days that I’m blocking the top I absolutely try everything! I put a direct link with “socket.io/socket.io.js” I changed port I redone my server.js code I reinstall express socket.io etc.. nothing works, do you have any idea what the problem is? I post my entire code:

server.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var players = {};
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
  console.log('a user connected');
  // create a new player and add it to our players object
  players[socket.id] = {
    rotation: 0,
    x: Math.floor(Math.random() * 700) + 50,
    y: Math.floor(Math.random() * 500) + 50,
    playerId: socket.id,
    team: (Math.floor(Math.random() * 2) == 0) ? 'red' : 'blue'
  };
  // send the players object to the new player
  socket.emit('currentPlayers', players);
  // update all other players of the new player
  socket.broadcast.emit('newPlayer', players[socket.id]);
  // when a player disconnects, remove them from our players object
  socket.on('disconnect', function () {
    console.log('user disconnected');
    // remove this player from our players object
    delete players[socket.id];
    // emit a message to all players to remove this player
    io.emit('disconnect', socket.id);
  });
});
server.listen(8081, function () {
  console.log(`Listening on ${server.address().port}`);
});

index.html :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <script src="/socket.io/socket.io.js"></script>
    <body>
        <script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>
        <script src="js/jeu1.js"></script>
    </body>
</html>

jeu1.js (the interesting part)


    function create ()
    {
      var self = this;
      this.socket = io();
     }

(I also did hours of research and searched for hours the answers that there were on stackoverflow)

Replicating Golang’s synchronous WaitGroup in JavaScript (node.js) using the Atomics API?

I am trying to replicate Golang’s WaitGroup in JavaScript using the Atomics API.

The reason I need this is to add control in certain callback APIs that don’t offer the ability to have async callbacks.

This is specifically for Node.js

A basic example:

import sqlite3 from 'sqlite3'

const db = new sqlite3.Database('./data.db')
const sleep = ms => new Promise(res => setTimeout(res, ms))

db.each('SELECT * from my_table', async (err, row) => {
  console.log('start', row)
  await sleep(2000)
  console.log('done', row)
});

Each iteration will not care for the Promise returned by the callback and will instead flip through all of the rows immediately. This API does not offer me the ability to go row by row to minimize CPU overhead.

While this is one example and perhaps the answer is to open a PR to the library, there are many similar examples and it’s more practical to have a solution I can implement on my end to address this while raising an issue with the maintainers.

I have since discovered the new Atomics API which offers the ability to sleep threads.

As an example here is a thread blocking sleep for 500ms.

const sleep = milliseconds => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds)

sleep(500)

Obviously it’s not ideal to use thread blocking techniques but in this case I believe it’s appropriate.

I would like to produce a wrapper around Atomics that allows for the same control flow management as Golang’s sync.WaitGoup

Assuming the following interface, producing a wrapper is challenging.

interface SyncWaitGroup {
   new (ticks: number): SyncWaitGroup
   done(): void
   wait(): void
}

Where its usage would be

db.each('SELECT * from my_table', (err, row) => {
  console.log('start', row)
  const wg = new SyncWaitGroup(1) // WaitGroup wants 1 call to done() 

  setTimeout(() => {
    wg.done() // This call will satisfy the required number of done() calls
  }, 2000)

  wg.wait() // synchronously wait for all the done() calls
  console.log('done', row)
});

Using this strategy to force the callback to be executed synchronously allows me to write a wrapper that converts db.each into an AsyncIterable where I could use it idiomatically from there.

The issue I am having is understanding the Atomics API. Attempting something like this fails as the thread (including the event loop) is sleeping and mutations to the input array are not tracked.

const arr = new Int32Array(new SharedArrayBuffer(4))

setTimeout(() => {
  arr[0] = 1
  console.log('fired')
}, 2000)

Atomics.wait(arr, 0, 0, 30_000)

How to make variable text fit into a div, with maximal font-size, in Vue3

I have a div that show a variable text. I want to give the max font-size possible to the text, without overflow. So if the text change, the font-size may also change.

So i made an algorithm comparing clientWidth and scrollWidth of this div. Each time an overflow is detected, i decrease the font-size of the div, then i wait for vue to upload the clientWidth and scrollWidth (await this.$nextTick()) and i do a new check.

That work well, but there is an exception.

When the component is mounted, scrollWidth as a bad value (not 0, but lower than the true scrollWidth). The scrollWidth become correct ~30ms after the mounted function of my component containing the div is fired. Even if i do a await this.$nextTick() on top of my mounted function. But if i change a file, triggering the hot-reload, then scrollWidth is correctly set when starting mounted function.

Can you explain me why please ? Is this a Vue3js bug ? How can i handle this ? There is an alternative to scrollWidth ?

My last idea is to use setTimeout to launch the algorithm after 30ms when scrollWidth is correctly setted. That works, but i dont like this solution, and the user see what the text is resized…

Maybe there is a todally different solution to make a variable text fit into a div with the max possible font-size ?

GSAP onComplete function doesn’t fire when scrolling up

I’m using react-gsap and react-scrollmagic and am trying to fire a function when the animation completes. It works well when I scroll down, however, when I scroll up the function doesn’t fire. I couldn’t find any reference to this problem in react-gsap documentation. Is there any solution to this?

    <Controller>
      <Scene triggerHook={0} duration={duration} pin={{ pushFollowers: false }}>
        {(progress) => (
          <Timeline totalProgress={progress} target={<p>wohoo</p>}>
            <Tween
              from={{ opacity: "0" }}
              to={{ opacity: "1" }}
              onStart={() => console.log("Complete!")} // Works only when scrolling down
              onComplete={() => console.log("Complete!")} // Works only when scrolling down
            />
          </Timeline>
        )}
      </Scene>
    </Controller>

dotenv d’ont work with createConnection what should I use instead?

Without using my .env file it work but when I it use to create a connection it fail.

var mysql = require('mysql');
require('dotenv').config();

const db = mysql.createConnection({
    host: process.env.HOST,
    port: "3306",
    user: process.env.USER,
    password: process.env.PASSWORD,
    database: process.env.DATABASE
});
module.exports = db

I have this error.

error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

But I’m already up to date with the last mysql version.

Any idea ?

When to use onclick ={ myfuntion()} vs onclick={() => (myfunction())}

Why is the id undefined in the randomCard function when using the onClick= {(randomCard()}
and defined when using onClick = {() => (randomCard())}

function Home() {
    const [cardlist, setCardList] = useState([]);
    const navigate = useNavigate()
    
    function randomCard() {
        const index = Math.floor(Math.random() * cardlist.length);
        const id = cardlist[index].id;
        navigate(`/cards/${id}`)
    }  

    useEffect(() => {
        async function fetchData() {
            const res = await axios.get('https://db.ygoprodeck.com/api/v7/cardinfo.php');
            const results = res.data;
            setCardList(results.data);
            console.log(cardlist);
        }
        fetchData();
    }, [])

    return (
        <div className='home'>
            <h1>Welcome to the Yu-Gi-Oh Database</h1>
            <p>Choose Option</p>
            <div className="options">
                <ul>
                    <li><a href='/allcards'>Show All Cards</a></li>
                    <li><a href='/'>Search Card</a></li>                    
                    <li><a href='' onClick={() => (randomCard())}>Random Card</a></li>                    
                </ul>
               
            </div>
        </div>
  )
}

How to test nextjs endpoint using Jest?

I have an endpoint that handles user signup:

import { createToken } './token'; // Unable to mock
import { sendEmail } './email'; // Unable to mock

export default async function signUp(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<any> {
  try {
    // Generate a verification token
    const token = await createToken(req.user);

    // Email the token
    await sendEmail(req.user, token);

    return res.status(200).send({ done: true });
  } catch (error: any) {
    console.error(error);
    return res.status(500).end(error.message);
  }
}

How do I mock the imported dependencies for my jest unit tests?

import signup from './signup';

describe('signup', () => {
  it('should return success', async () => {
    const req: IncomingMessage = {} as unknown as IncomingMessage;
    const res: ServerResponse = {
      end: jest.fn(),
    } as unknown as ServerResponse;

    const actual = await signup(req, res);

    ...
  });
});

Is it the case that Jest cannot actually mock these nested dependencies and some sort of DI pattern needs to be implemented here in the endpoint? If so, what DI patterns can I use to support unit tests for Nextjs endpoints?

owl-carousel-o is showing item vertically

i’m using Angular and i want to show items in normal way (using owl-carousel-o) , but that’s how they’re shown in the Link

that’s the app.component.ts code

    import { Component,OnInit, HostListener } from '@angular/core';
import { OwlOptions } from 'ngx-owl-carousel-o';
import { MatCarousel, MatCarouselComponent } from '@ngmodule/material-carousel';
import {MatBottomSheet, MatBottomSheetRef} from '@angular/material/bottom-sheet';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'projet';

  
  slides = [
    {'image': 'https://picsum.photos/seed/picsum/1200/300'}, 
    {'image': 'https://picsum.photos/seed/picsum/1200/300'},
    {'image': 'https://picsum.photos/seed/picsum/1200/300'}, 
    {'image': 'https://picsum.photos/seed/picsum/1200/300'}, 
    {'image': 'https://picsum.photos/seed/picsum/1200/300'}
  ];
// Product Slider
customOptions: any = {
    loop: false,
    dots: false,
    navSpeed: 300,
    responsive: {
        991: {
            items: 4
        },
        767: {
            items: 3
        },
        420: {
            items: 2
        }, 
        0: {
            items: 1
        }
    }
}
      slidesStore = [

      {id: "1", img: "https://dummyimage.com/350x150/423b42/fff"},

      {id: "2", img: "https://dummyimage.com/350x150/2a2b7a/fff"},

      {id: "3", img: "https://dummyimage.com/350x150/1a2b7a/fff"},

      {id: "4", img: "https://dummyimage.com/350x150/7a2b7a/fff"},


    ];
// <HTMLInputElement>document.getElementById("navbar");

}

this is HTML code

<owl-carousel-o [options]="customOptions">

    <ng-container *ngFor="let slide of slidesStore">
      <ng-template carouselSlide [id]="slide.id">
        <img [src]="slide.img" >
      </ng-template>
    </ng-container>

  </owl-carousel-o>

i did import it in app.module.ts

i’ve tried many solutions online but nothing works

any solution ?