I get mime type error when I connect my react app(via vite.js) with django framework

recently I’m starting to make a web application with React and Django. I installed react with vite.js(because it seems so fast in the development environment). and I connected it to Django web framework and ran it. and I thought It would show basic react page(you know, dark page and favicon is revolving ) However, contrary to my expectations, It only shows blank and I checked the console.log. the error message was this : Refused to apply style from 'http://127.0.0.1:8000/assets/index.cd9c0392.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

so I googled it and figure out that is a problem with the path in most cases. but when I check the my index.html in build file, path seems fine. below is my build folder structure and index.html, can you tell me what is wrong with my code or logic or both? thx for reading , your help will be appreciated.

frontend
-dist => this is build folder
--assets
---index.cd9c0392.css
---favicon.21sd12.js
 .
 .    
 .
--index.html
-node_modules
-src
-index.html
.
.
.

index.html(in dist)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/assets/favicon.17e50649.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
    <script type="module" crossorigin src="/assets/index.3e288fda.js"></script>
    <link rel="modulepreload" href="/assets/vendor.dc18184a.js">
    <link rel="stylesheet" href="/assets/index.cd9c0392.css">
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

P.S I also get these following errors too which I assume same type of errors with above FYI.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
vendor.dc18184a.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
main.jsx:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Adding symbol in json files

I have not been able to add a “&” symbol in a “page-info.json” file as a text.

Example:

“copy”: “Click here to request design, video & layout support”

Please note:

The & symbol worked in other page-info.json project files before (React, Carbon).

However, for some reason, the “&” symbol appears (when using shift+7) in VSCODE, but is not appearing in the page preview itself.

I’ve tried using (backslash&) and (&amp 😉 already, but is not working either.

The only option that worked was using the command Control + Command + Spacebar keys in order to use the “&” as an emoji. The thing is … the emoji disappears when changing the responsive layout.

Could someone please help me?

Thanks in advance.

I needed to make a list in Javascript, but to no avail

I’m using an API and I wanted to extract the API URLs, for this I made a code, but only a url appears, I will give example of the JSON code of the API.
Not to mention that a title comes, then comes in order first title and then the URL

{
 "items": [
   "title":"YouTube",
   "url":"https://www.youtube.com/",
   "title":"Google",
   "url":"https://www.google.com/",
   "title":"Facebook",
   "url":"https://www.facebook.com/",
   "title":"Github",
   "url":"https://www.github.com",
   "title":"Microsoft",
   "url":"https://www.microsoft.com"
 ]
}

It’s not exactly these urls, I used it as an example.

I would like to extract this information and leave as follows:

[Title](Url)

I want it to look like this, because the title will turn blue and when you click it goes to the site URL.

My code that didn’t work out is this:

        const embed = new MessageEmbed()
            .setColor("#ffff00")
            .setDescription(`[${info.title}](${info.url})n`)

        await message.channel.send({
          embed: embed,
          buttons: btn
          });

This info.url is where you get the URL and info.title is where you get the title, only there’s only 1 problem, it takes only 1 title and 1 url, I would like you to take them all and form a list in The Discord Bot

This is the result of the code:
enter image description here

But I wanted it to look like this:
Youtube
Google
Facebook
Github
Microsoft

So that only youtube appears

And when you click on each title, be redirected to the site.

is it alright to have a ref on state (from a reducer) to avoid creating new callbacks?

I often have a use case where there is some state in reducer and it needs to be accessed in some callback (useCallback) as well

const [state, dispatch] = useReducer(reducer, initialState);
...
const handleAction = useCallback(()=>{
   // dependency on state 
},[])

to avoid running useCallbacks on every state change, I reach out for a ref and have the state assigned to it on every render

 stateRef.current = state;

and then where ever i have to use something from state in a callback, it is accessed from the stateRef. Is this a right way of doing it?

The reason why clicking on one checkbox deactivates the entire input

I’m facing a problem that I seem to know but I don’t know. I made “State” by [checked]. There is a problem that if you turn this to the map and click only one checkbox, the whole is clicked. So I put {cked[idx]} to solve it, but my senior advised me that there was a problem with the code.
Because [checked] is in the form of “Boolean” and idx is “number”.

And input has a ‘disabled’ attribute. I know that this is also deactivated as a whole because I put ‘checked’ in. By the way, I want each of them to be deactivated when I press the check box. But I don’t know how. I searched for stack overflow, but I couldn’t find a similar case to mine.
I believe you guys can help me.

const [checked, setChecked] = useState(false);
.
.
.
{keys &&
          keys?.map((item: any, idx: number) => {
            return (
              <div key={idx}>
                <Box component="form" className={classes.Box}>
                  <div className={classes.typeText}>{item.columnName}</div>
                  <div className={classes.flexWrap}>
                    <TextField
                      id="outlined-basic"
                      label={item.type}
                      variant="outlined"
                      className={classes.filled}
                      disabled={checked} //hear❗️
                    />
                    <FormControlLabel
                      value="end"
                      control={
                        <Checkbox
                          className={classes.checkBox}
                          color="primary"
                          checked={checked[idx]} //hear❗️
                          onChange={handleCheckboxChange}
                        />
                      }
                      label="Null"
                      labelPlacement="end"
                    />
                  </div>
                </Box>
              </div>
            );
          })}

Having issues with deleting object from an array where match is found

I have the follow function that will delete object from array. It also returns the array tree without the items that was deleted. My issues is that it works when my objToFindBy is null deleting everything where {group: null} is found however it error with promise rejection if I set objToFindBy {group: ‘some string’}

This code should delete all occurrences where the objToFindBy is a match, example {group: null} will find everywhere will the group is null and delete all object and then return the full tree without the objects that was deleted

findAndDeleteAll(tree, 'items', {group: null}) // work and delete all where match. then returns the tree without deleted objects

findAndDeleteAll(tree, 'items', {group: 'd575c91f-4765-4073-a948-5e305116610c'}) // promise rejection
const tree ={
    "type": "app",
    "info": "Custom Layout",
    "items": [
      {
        "id": "d575c91f-4765-4073-a948-5e305116610c",
        "title": "Fc",
        "group": null
      },
      {
        "id": "890d5a1e-3f03-42cd-a695-64a17b6b9bea",
        "title": null,
        "group": null
      },
      {
        "id": "cbe00537-0bb8-4837-8019-de48cb04edd6",
        "title": null,
        "group": "d575c91f-4765-4073-a948-5e305116610c",
      },
      {
        "id": "b8751c32-2121-4907-a229-95e3e49bcb39",
        "title": null,
        "group": "d575c91f-4765-4073-a948-5e305116610c"
      }
    ],
    "Children": []
  }
var findAndDeleteAll = function findAndDeleteAll(tree, childrenKey, objToFindBy) {
      var treeModified = false;
      var findKeys = Object.keys(objToFindBy);
      var findSuccess = false;
      findKeys.forEach(function (key) {
        (0, _lodash2.default)(tree[key], objToFindBy[key]) ? findSuccess = true : findSuccess = false;
      });
      if (findSuccess) {
        Object.keys(tree).forEach(function (key) {
          return delete tree[key];
        });
        return tree;
      }
      function innerFunc(tree, childrenKey, objToFindBy) {
        if (tree[childrenKey]) {
          var _loop = function _loop(index) {
            var findKeys = Object.keys(objToFindBy);
            var findSuccess = false;
            findKeys.forEach(function (key) {
              (0, _lodash2.default)(tree[childrenKey][index][key], objToFindBy[key]) ? findSuccess = true : findSuccess = false;
            });
            if (findSuccess) {
              tree[childrenKey].splice(index, 1);
              treeModified = true;
            }
            if (tree[childrenKey][index].hasOwnProperty(childrenKey)) {
              innerFunc(tree[childrenKey][index], childrenKey, objToFindBy);
            }
          };
    
          for (var index = tree[childrenKey].length - 1; index >= 0; index--) {
            _loop(index);
          }
        }
      }
      innerFunc(tree, childrenKey, objToFindBy);
      return treeModified ? tree : false;
    };

Node.js – Using Multer to upload images in MongoDB and having trouble updating them

I was able to successfully upload images in my MongoDB project using Multer, but I’m stuck on how to update them. When I tried using the same trick in my Edit function, the log says I can’t set headers after they’re sent to the client. For context, I’ll put in my code for uploading and editing

router.get('/upload', IsLoggedIn, (req, res, next) => {
    res.render('mods/upload', {title: 'Upload a mod', user: req.user});
    res.sendFile(path.join(__dirname, './mods/upload.hbs'));
});

router.post('/upload', upload.single('image'), IsLoggedIn, (req, res, next) => {
    console.log(req.file);
    Mod.create({
        name: req.body.name,
        image: req.file.filename,
        file: req.body.file
    }, (err, newMod) => {
        if (err) {
            console.log(err);
        }
        else {
            res.redirect('/mods');
        }
    });
});
router.get('/edit/:_id', IsLoggedIn, (req, res, next) => {
        Mod.findById(req.params._id, (err, mod) => {
            if (err) {
                console.log(err);
            }
            else {
                res.render('mods/edit', {
                    title: 'Edit mod',
                    mod: mod,
                    user: req.user
                })
            }
        }).sort({name: 1});
        res.render('mods/edit');
        res.sendFile(path.join(__dirname, './mods/edit.hbs'));
    });

    router.post('/edit/:_id', upload.single('image'), IsLoggedIn, (req, res, next) => {
       Mod.findOneAndUpdate(
            {
                _id: req.params._id
            },
            {
                name: req.body.name,
                image: req.file.filename,
                file: req.body.file
            },
            (err, updatedProject) => {
                if (err) {
                    console.log(err);
                }
                else {
                    res.redirect('/mods');
                }
            }
        )
    });

Am I even able to update images in the same fashion, or is there something entirely different I should be doing? I’m still super new to Multer and I haven’t done a whole lot with MongoDB, so any guidance would be super appreciated!

How is this assignment working? (js/ svelte) [duplicate]

I’m following the svelte tutorial and I don’t see how this assignment on line 10 of the tick page in chapter 7 linked here is working.

 const { selectionStart, selectionEnd, value } = this;

this doesn’t have selectionStart and selectionEnd defined at this point in the code, and when it does assign them it uses those values, which seems like a loop to me. I just don’t see where they’re coming from or how this doesn’t produce an error.

Open link in another browser

<button>open in another browser</button>

 

const btn = document.querySelector('button') 
btn.addEventListener('click', () => {
    window.open('https://example.com', '_blank')
})

Assume the HTML button above will be viewed in an Android WebView.

I need the link to open in an external browser. For this, I know that it is necessary to program both on the front-end and on the back-end.

In Java, for another application to open the link as expected, you need to use Intent, as shown in this post:
https://stackoverflow.com/a/17994857

What I need to know is how to program JavaScript so that _blank is understood by Java as a link that must be opened externally.

How to deconstruct a string using Google App Script

I’m working within Google Sheets and passing information from multiple sheets to another. However, when the user inputs their Reps and Weight into a form (That then sends the information to Google Sheets), it places ALL of that info within a single cell.

So, cell “C2” will receive:

“Reps: 15, Weight: 150
Reps: 12, Weight: 175
Reps: 10, Weight: 200
Reps: 8, Weight: 225
Reps: 6, Weight: 250”

In the form of one single cell.

Using App Script, how can I dissect this single cell to have access to the numbers so I can place each one into a different corresponding cell?

I want to be able to move 15 to “C4” and 150 to “C5” and so on. I don’t need any of the words etc, just the numbers saved into separate variables.

Create div and carousel based on the number of elements in an array of objects

I have to create a carousel (so with the dots useful for scrolling the images, Next/previous buttons, number text) with the appropriate divs based on the number of elements in the array.

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("img");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = slides.length
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";
}

function myFunction1() {
  var xmlhttp = new XMLHttpRequest();
  var url = "https://wjko5e2643.execute-api.us-east-2.amazonaws.com/books";
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myArr = JSON.parse(this.responseText);
      var id = myArr.Item.id;
      document.getElementById("img1").src = myArr.Item.image;
      var id = myArr.Item.id;
      document.getElementById("title1").innerHTML = `<a href="books.html?id=${id}">${myArr.Item.title}</a>`;
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}
* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

.img {
  display: none
}

img {
  vertical-align: middle;
}


/* Slideshow container */

.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}


/* Next & previous buttons */

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}


/* Position the "next button" to the right */

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}


/* On hover, add a black background color with a little bit see-through */

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}


/* Caption text */

.text {
  color: #f2f2f2;
  font-size: 50px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}


/* Number text (1/2 etc) */

.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}


/* The dots/bullets/indicators */

.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active,
.dot:hover {
  background-color: #717171;
}


/* Fading animation */

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}


/* On smaller screens, decrease text size */

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

  <div class="slideshow-container">

    <div class="img fade">
      <div class="numbertext">1 / 2</div>
      <img id="img1" src onerror="this.onerror=null; this.src=myFunction1();" style="width:100%">
      <div class="text" id="title1" onclick="myFunction1()"></div>
    </div>

    <div class="img fade">
      <div class="numbertext">2 / 2</div>
      <img id="img2" src onerror="this.onerror=null; this.src=myFunction2();" style="width:100%">
      <div class="text" id="title2" onclick="myFunction1()"></div>
    </div>

    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>

  </div>
  <br>

  <div style="text-align:center">
    <span class="dot" onclick="currentSlide(1)"></span>
    <span class="dot" onclick="currentSlide(2)"></span>
  </div>


</body>

</html>

The following example refers to two images; so the numbertext must automatically update based on the number of elements in the array and so the various elements that compose it and therefore have only one “dynamic” div.

Can anyone kindly help me?

How to get correct navigation state for prev/next methods for custom React-Waypoint hook?

At the moment, I’m creating two hooks for the React-Waypoint component.

What is React Waypoint?

React-Waypoint lets you monitor the scroll position of your browser and once it hits the waypoint it fires an “enter” event, once it is leaving the screen it fires the “leave” event.

useWaypoint hook

This hook can be used to to create waypoints.

Usage example

const [Waypoint, { scrollToWaypoint }] = useWaypoint({
    component: <div>If I'm visible I will trigger an event!</div>,
    enter: () => console.log("waypoint enter"),
    leave: () => console.log("waypoint leave")
  });

return (
    {/* other content */}
    <Waypoint/>
)

With this, it will trigger the enter/leave events once the waypoint div gets visible/invisible.
The method scrollToWaypoint can be used to scroll to the element.

useWaypointNavigation hook

The idea is to have a navigation between waypoints. With previous and next buttons (see below screenshot).

This is where I’m having the following issues:

  • Fast scrolling creates an inconsistent state but not sure why (this can be fixed later)
  • The main issue is that the first and last prev/next navigation is not working if scrolled manually before clicking.

Scrolling issue

Scroll the screen so that “w0” is visible (like in the below screenshot), then click next. The expected behavior is to scroll “w0” into view but it scrolls to “w1”.
w0 scroll position

Same issue at the last position. Scroll below “w3” and hit prev. The expected behavior is to scroll “w3” into view but it scrolls to “w2”.

w3 scroll position

Maybe it’s just logic that’s missing but I’m struggling with it for some time now and I’m not sure how to fix this.

How does the hook work?

First, the useWaypoint hooks are initialized in an array

const waypoints: Array<UseWaypointReturn> = [
    useWaypoint({
      component: <Box index="w0" />,
      enter: enter("w0"),
      leave: leave("w0")
    }),
    useWaypoint({
      component: <Box index="w1" />,
      enter: enter("w1"),
      leave: leave("w1")
    }),
    useWaypoint({
      component: <Box index="w2" />,
      enter: enter("w2"),
      leave: leave("w2")
    }),
    useWaypoint({
      component: <Box index="w3" />,
      enter: enter("w3"),
      leave: leave("w3")
    })
  ];

And then passed to the hook, so the hook get the information about each waypoint.

  const {
    visibilityMap,
    nextWaypointIndex,
    prevWaypointIndex,
    next,
    prev
  } = useWaypointNavigation({ waypoints });

The return values from the hook are some debug information and the next and prev method that scroll to the next or prev. waypoint.

visibilityMap is used to determine the prev / next index. The index is the position in the waypoints array, so we can use the scrollToWaypoint method.

The logic of the prev/next index calucalation is inside the useEffect:

  1. Iterate through the visibilityMap e.g. [false,false,true,false] to determine the last visible index lastVisibleIndex and the visibleCount
  2. Two cases here:
  • If one item is visible, we can use the lastVisibleIndex to calculate the prev & next index
  • If two items are visible, we’re taking the lastVisibleIndex as the next index as we’re between two waypoints –> could be problematic for 3 visible but it’s working
  1. Special case: Scrolled below all waypoints should hold the last waypoint. With-out holding it was resetting prev and next index to zero. Holding works but there is something missing to get the expected behavior.

Any ideas are highly appreciated. Would be great if I’m just not seeing the cause and there is an easy fix.

Things I’ve tried:

  • onPositionChange or onEnter / onLeave are containing information about the position but I couldn’t get it to work (maybe I have to check this again). Position information is “inside”, “above”, “below” but the previousPosition wasn’t helping (most of the time it was undefined)
  • Tried to add more logic around lastVisibleIndex or visibibleCount but without success

Source code

You can find the code in the following Codesandbox and below.

useWaypoint hook

import React, {
  FC,
  MutableRefObject,
  ReactNode,
  useRef,
  useState
} from "react";

import { Waypoint } from "react-waypoint";

type useWaypointProps = {
  enter?: () => void;
  leave?: () => void;
  component?: ReactNode;
};

export type UseWaypointReturn = [
  FC<any>,
  {
    ref: MutableRefObject<ReactNode>;
    isVisible: boolean; ///> true = waypoint entered & not left yet
    scrollToWaypoint: () => void;
  }
];

interface IUseWaypoint {
  (props: useWaypointProps): UseWaypointReturn;
}

export const useWaypoint: IUseWaypoint = ({
  component,
  enter,
  leave,
  ...hookProps
}) => {
  const waypointRef = useRef<HTMLDivElement | null>(null);
  const [isVisible, setVisible] = useState(false);

  const scrollToWaypoint = () => {
    if (waypointRef && waypointRef.current) {
      waypointRef.current.scrollIntoView({
        block: "start",
        behavior: "smooth"
      });
    }
  };

  const onEnter = () => {
    setVisible(true);
    if (enter) {
      enter();
    }
  };

  const onLeave = () => {
    setVisible(false);
    if (leave) {
      leave();
    }
  };

  return [
    ({ children, ...props }) => (
      <div ref={waypointRef}>
        <Waypoint
          debug={false}
          {...props}
          {...hookProps}
          onEnter={onEnter}
          onLeave={onLeave}
        >
          {component ? <div>{component}</div> : <div>{children}</div>}
        </Waypoint>
      </div>
    ),
    {
      ref: waypointRef,
      isVisible,
      scrollToWaypoint
    }
  ];
};

useWaypointNavigigation hook

import React, { FC, useEffect, useState } from "react";
import "./styles.css";
import { useWaypoint, UseWaypointReturn } from "./hooks/useWaypoint";

// Issues:
// - Fast scrolling missing leave events? --> inconsistent navigation state
//   --> check "rapid fire" prop on Waypoint component - should be active by default
//
// Todo:
// - Add prev - next waypoint - requires a check which waypoints are on screen
//   --> create hook useWaypointNavigation

type useWaypointNavigationProps = {
  waypoints: Array<UseWaypointReturn>;
};

type UseWaypointNavigationReturn = {
  next: () => void;
  prev: () => void;
  nextWaypointIndex: number;
  prevWaypointIndex: number;
  visibilityMap: Array<Boolean>;
};

interface IUseWaypointNavigation {
  (props: useWaypointNavigationProps): UseWaypointNavigationReturn;
}

const createVisiblityMap = (
  waypoints: Array<UseWaypointReturn>
): Array<Boolean> => waypoints.map((w: any) => w[1].isVisible);

const useWaypointNavigation: IUseWaypointNavigation = ({ waypoints }) => {
  const visibilityMap = createVisiblityMap(waypoints);
  const [holdLastWaypoint, setHoldLastWaypoint] = useState(false);
  const [nextWaypointIndex, setNext] = useState(0);
  const [prevWaypointIndex, setPrev] = useState(0);

  /*
  // not needed as we're calculating prev/next from waypoints
  // (were used for testing prev/next scrolling)
  // --> can be tested if useEffect block is commented
  const incrementWaypointIndex = () => {
    const lastWaypointIndex = waypoints.length - 1;
    if (nextWaypointIndex + 1 < lastWaypointIndex) {
      setPrev(nextWaypointIndex);
      setNext(nextWaypointIndex + 1);
    } else {
      setPrev(lastWaypointIndex - 1);
      setNext(lastWaypointIndex);
    }
  };

  const decrementWaypointIndex = () => {
    if (prevWaypointIndex - 1 >= 0) {
      setPrev(prevWaypointIndex - 1);
      setNext(prevWaypointIndex);
    } else {
      setPrev(0);
      setNext(0);
    }
  };*/

  useEffect(() => {
    console.log("update next / prev index");
    const mapLength = visibilityMap.length;
    // "scroll fast issue" --> why?
    // Visibility map inconsistent and can't be used to detect
    // position

    // true = one waypoint in view
    // true, true = two waypoints in view --> next = last true
    // special case all false --> above or below
    // -- waypoints "below" handled by visibility count + start values
    // -- waypoints "above" handled by holding last prev/next by disabling updating
    let lastVisibleIndex = 0;
    let visibleCount = 0;
    visibilityMap.forEach((val, index) => {
      if (val) {
        visibleCount++;
        lastVisibleIndex = index;

        if (mapLength - 1 === index) {
          // last element visible --> hold setting
          setHoldLastWaypoint(true);
        } else {
          setHoldLastWaypoint(false);
        }
      }
    });

    let next;

    if (visibleCount === 1) {
      // only one element in view -> +1 to get next waypoint index
      next =
        lastVisibleIndex + 1 >= mapLength
          ? mapLength - 1
          : lastVisibleIndex + 1;
    } else {
      // one or more items visible -> last element in view = next element
      next = lastVisibleIndex;
    }

    if (!holdLastWaypoint) {
      // only update if not holding last waypoint
      // --> holding needed if waypoints are scrolled out of view
      //     so they're above and we'd like to navigate back
      setPrev(lastVisibleIndex > 1 ? lastVisibleIndex - 1 : 0);
      setNext(visibleCount === 0 ? 0 : next);
    }
  }, [
    visibilityMap,
    holdLastWaypoint,
    setHoldLastWaypoint,
    setNext,
    setPrev,
    nextWaypointIndex,
    prevWaypointIndex
  ]);

  return {
    next: () => {
      waypoints[nextWaypointIndex][1].scrollToWaypoint();
    },
    prev: () => {
      waypoints[prevWaypointIndex][1].scrollToWaypoint();
    },
    nextWaypointIndex, // just for debugging
    prevWaypointIndex,
    visibilityMap
  };
};

type BoxProps = {
  index?: string | number | null;
};

const Box: FC<BoxProps> = ({ index }) => (
  <div className="box">
    <h1>{index}</h1>
  </div>
);

const Spacer: FC = () => (
  <div style={{ height: "1000px", border: "1px solid red" }}></div>
);

export default function App() {
  const enter = (index: number | string) => () => {
    console.log(`waypoint ${index} enter`);
  };

  const leave = (index: number | string) => () => {
    console.log(`waypoint ${index} leave`);
  };

  /*
  Re-add usage demo later
  const [Waypoint0, { scrollToWaypoint: scrollWay0 }] = useWaypoint({
    component: <Box index="0" />,
    enter: enter(0),
    leave: leave(0)
  });

  const [Waypoint1] = useWaypoint({
    //component: <Box index="0" />,
    // added as child to Waypoint1
    enter: enter(1),
    leave: leave(1)
  });

  const [WaypointInvisble] = useWaypoint({
    //component: <Box index="0" />,
    // with-out component or children to have a invisible waypoint
    enter: enter("invisible"),
    leave: leave("invisible")
  });
  */

  const waypoints: Array<UseWaypointReturn> = [
    useWaypoint({
      component: <Box index="w0" />,
      enter: enter("w0"),
      leave: leave("w0")
    }),
    useWaypoint({
      component: <Box index="w1" />,
      enter: enter("w1"),
      leave: leave("w1")
    }),
    useWaypoint({
      component: <Box index="w2" />,
      enter: enter("w2"),
      leave: leave("w2")
    }),
    useWaypoint({
      component: <Box index="w3" />,
      enter: enter("w3"),
      leave: leave("w3")
    })
  ];

  const {
    visibilityMap,
    nextWaypointIndex,
    prevWaypointIndex,
    next,
    prev
  } = useWaypointNavigation({ waypoints });

  return (
    <div className="App">
      <div className="controls">
        <button onClick={waypoints[0][1].scrollToWaypoint}>
          Scroll to Waypoint w0
        </button>
        <h3>Debug</h3>
        <pre>
          {JSON.stringify(visibilityMap, null, 2)}
          <br />
          next {nextWaypointIndex}
          <br />
          prev {prevWaypointIndex}
          <br />
          <button onClick={prev}>Prev</button>
          <button onClick={next}>Next</button>
        </pre>
      </div>
      <Spacer />
      {/* Re-add the usage demo later
      <Waypoint0 />
      <Waypoint1>
        <h2>Also possible to add the content here</h2>
      </Waypoint1>
      <WaypointInvisble />
      */}

      {/* more waypoints (named w0, w1, w2,...*/}
      {waypoints.map((w, i) => {
        // index 0 = Component,
        // index 1 = {ref, scrollToWaypoint, ...rest}
        const Waypoint = w[0];
        return <Waypoint key={i} />;
      })}
      <Spacer />
    </div>
  );
}

How to reset CSS transitions on navigation

I have been trying to figure out the best way to reset my CSS transitions for my website’s navigation on mobile. The transitions only work the first time the page is loaded and after some research it seems that I need to reset them on click with Javascript or jQuery (I’m unfamiliar with both, hence why this has become an issue.) Any ideas would be appreciated. As a side note, I am using Divi for this website which is the reason for the overcomplicated class names and hierarchy.

Link to website: https://penmenwriting.com/

CSS below:

/* Mobile Navigation */


#mobile_menu1,  .opened #mobile_menu1 {
    position: fixed;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 100%;
    max-height: 100%;
    z-index: 10;
    top: 0;
    border: none;
    overflow-y: auto;
    max-width: 100%;
    float: left;
    transition: all cubic-bezier(0.5, 0, 0, 1) 800ms;
    background-color: rgba(0,0,0,1);
    background-size: cover;
    background-repeat: no-repeat;
}

.opened #mobile_menu1 {
    transform: none;
}
.opened #mobile_menu1 a {
    transform: none;
    opacity: 1;
}
.opened #mobile_menu1 .menu-item:nth-child(1) a, .closed #mobile_menu1 .menu-item:nth-last-child(1) a {
    transition-delay: 200ms;
}

.opened #mobile_menu1 .menu-item:nth-child(2) a, .closed #mobile_menu1 .menu-item:nth-last-child(2) a {
    transition-delay: 300ms;
}

.opened #mobile_menu1 .menu-item:nth-child(3) a, .closed #mobile_menu1 .menu-item:nth-last-child(3) a {
    transition-delay: 400ms;
}

.opened #mobile_menu1 .menu-item:nth-child(4) a, .closed #mobile_menu1 .menu-item:nth-last-child(4) a {
    transition-delay: 500ms;
}

.opened #mobile_menu1 .menu-item:nth-child(5) a, .closed #mobile_menu1 .menu-item:nth-last-child(5) a {
    transition-delay: 600ms;
}

.opened #mobile_menu1 .menu-item:nth-child(6) a, .closed #mobile_menu1 .menu-item:nth-last-child(6) a {
    transition-delay: 700ms;
}
.mobile_menu_bar {
    z-index: 100;
}
.mobile_nav.opened .mobile_menu_bar:before {
 content: '4d';
    color: #262626;
    transition: all ease-in-out 500ms;
    z-index: 100;
}

.mobile_nav.closed .mobile_menu_bar:before {
    transition: all ease-in-out 300ms;
}
/* Menu animations */

.closed #mobile_menu1 {
    opacity: 0;
    pointer-events: none;
    transform: translatex(-100%);
    width: 0px;
    transition-delay: 600ms;
}

/* Link animations */

#mobile_menu1 a {
    transform: translatex(-90px);
    opacity: 0;
    transition: all cubic-bezier(0.5, 0, 0, 1) 800ms;
    text-align: left;
}

/* Stop body from scrolling while in nav */
body.noscroll {
    overflow-y: hidden;
}

images sequence animation on scroll with canvas

I want to develop an images sequence inside a canvas based on mouse scrollin:
when the sequence ended the canvas has to stop being fixed restoring a standard scroll
that reveils the content under the sequence, how can do that?

this is the pen
https://codepen.io/balestra78/pen/rNGqyyE

this is the code

— HTML —

<canvas id="hero-lightpass"></canvas>
  <div id="lipsum">... content after sequence ...</div>

— CSS —

body {
  padding: 0;
  margin: 0;
}

canvas {
  position: fixed;
}

#lipsum {
  padding-top: 900px;
  height: 200vh;
}

— JS —

const html = document.documentElement;
const canvas = document.getElementById("hero-lightpass");
const lipsum = document.getElementById("lipsum");
const context = canvas.getContext("2d");

const frameCount = 49;
const currentFrame = index => (
  `https://calcionapp.it/test/AdobeStock_320972514_Video_HD_Preview${index.toString().padStart(4, '0')}.jpg`
)

const preloadImages = () => {
  for (let i = 1; i < frameCount; i++) {
    const img = new Image();
    img.src = currentFrame(i);
  }
};

const img = new Image()
img.src = currentFrame(1);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.onload = function () {
  scaleToFill(this)
}

const updateImage = index => {
  img.src = currentFrame(index);
  scaleToFill(img)
}

window.addEventListener('scroll', () => {
  const scrollTop = html.scrollTop;
  const maxScrollTop = html.scrollHeight - window.innerHeight;
  const scrollFraction = scrollTop / maxScrollTop;

  const frameIndex = Math.min(
    frameCount - 1,
    Math.ceil((scrollFraction * frameCount))
  );
  requestAnimationFrame(() => updateImage(frameIndex + 1))
  if (frameIndex > 47) {
    canvas.style.position = 'relative';
  } else {
    canvas.style.position = 'fixed';
  }
});

function scaleToFill(img) {
  // get the scale
  var scale = Math.max(canvas.width / img.width, canvas.height / img.height);
  // get the top left position of the image
  var x = (canvas.width / 2) - (img.width / 2) * scale;
  var y = (canvas.height / 2) - (img.height / 2) * scale;
  context.drawImage(img, x, y, img.width * scale, img.height * scale);
}

preloadImages()