How to add a delay to an animation if it’s in the viewport initially, otherwise have a different delay?

I’m trying to build a website using React and framer motion and I’m running into a challenge.

If an element is in the viewport when the page initially loads, I want there to be a delay on the animation. But if the element isn’t in the viewport, and the user has to scroll to see it, I want there to be a different delay value.

So for example, on my website I have a header Lorem ipsum and some text that I render first. Then I have a Projects header that renders second. And lastly, a My Project block that renders third.

animation 1

This looks great if the window height is big enough so that everything loads in at once.

But if the window height is smaller, like in the GIF below, the My Project block takes too long to load in.

animation 2

I’d like to have it so that it loads in faster like this:

animation 3

I tried searching online to see if someone has had this problem before, but I couldn’t find any posts online about this.

Any ideas on how to solve this?

My code:

// page.tsx

<main>
  <div>
    <motion.h1
      initial={{ opacity: 0, y: 10 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ ease: 'linear', duration: 0.5, delay: 0.15 }}
    >
      Lorem ipsum
    </motion.h1>
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ ease: 'linear', duration: 0.5, delay: 0.15 }}
    >
      <h1>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
        tempor incididunt ut labore
      </h1>
      <h1>
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
      </h1>
    </motion.div>
  </div>
  <motion.h2
    initial={{ opacity: 0, y: 10 }}
    animate={{ opacity: 1, y: 0 }}
    transition={{ ease: 'linear', duration: 0.5, delay: 0.8 }}
  >
    Projects
  </motion.h2>
  <div>
    <Card
      title={cards[0].title}
      description={cards[0].description}
      index={0}
    />
  </div>
</main>
// Card.tsx

type CardProps = {
  title: string;
  description: string;
  index: number;
};

export default function Card({
  title,
  image,
  altText,
  slug,
  index,
  description,
}: CardProps) {
  delay =  1.05 + index * 0.2; // default delay
  // delay = 0.25; // delay I want if it's not in the viewport on first page load

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{
        ease: 'linear',
        duration: 0.5,
        delay: delay,
      }}
    >
      <p>{title}</p>
      <p>{description}</p>
      <a>
        Learn more
        <svg>...</svg>
      </a>
    </motion.div>
  );
}

number_format field not working as expected

I need your help again. I have to create a new product that contain many raw materials.
To do that I have 3 steps:

  1. open a web page with info about RM used for this product;add ProductQty to be created
  2. send email with information about the product created;
  3. update database;
    Everything works fine for RawMaterial_Qty in page 2 and 3 where I use:
<? php echo number_format($weight, ($weight < 6 ? 2 : 0), '.', ''); ?>;

In the first page my code for RawMaterial_Qty is:

$(this).find('.kg').html(cmp_value.toFixed(2));

I tried the bellow code but it is not working

$(this).find('.kg').html(format_val(cmp_value < 6 ? Number(cmp_value.toFixed(2)) : Number(cmp_value.toFixed(0))));  

I am not a developer. What is wrong with this code? ….Thank you again.

cropper container expand beyond img height

I have this code to upload an image via dropzone js then handed over to cropper before uploading it to server. The issue I have is with images with heights above 1000 px. the container expand almost 3-4X the image height.

<div>
<canvas id="logocanvas">
</canvas>
</div>

var $canvas = $('#logocanvas'),         
context = $canvas.get(0).getContext('2d');


Dropzone.options.singleupload = {
   paramName: 'logo',  // The name that will be used to transfer the file
   maxFiles: 1,            // number of files 
   uploadMultiple: false,
   maxFilesize: 4,         // File size in Mb
   addRemoveLinks: true,   // allow files delete
   acceptedFiles: 'image/jpeg,image/png,image/gif',
   init: function() {
       this.on("success", function(file, responseText) {
           if (this.files && this.files[0]) {
               original =  this.files[0].dataURL;              
               if ( this.files[0].type.match(/^image//) ) {
                   var reader = new FileReader();
                   reader.onload = function(e){                    
                       var img = new Image();                              
                       img.onload = function() {
                           setTimeout(function() {    
                               context.canvas.width = img.width;       
                               context.canvas.height = img.height;     
                               context.drawImage(img, 0, 0);
                               var cropper = $canvas.cropper({     
                                   aspectRatio: 1,                     
                               });
                           }, 500);
                       };
                       img.src = e.target.result;
                   };
                   reader.readAsDataURL(this.files[0]);
               }
           }
       });
       this.on("removedfile", function(file, responseText) {
       });
   }
}

This is what i get with an image height of 4000 px
enter image description here

jQuery button click not showing/hiding content

I just started working with Javascript, and I’m unable to get the <p>p elements in <article id="main">article.

Again, I’m new so sorry in advance for my lack of knowledge. I have added the 2 <script> at the bottom of the body element to connect the JS to the HTML.

Here’s where I’m at:

Html code:

<!DOCTYPE html>
<!-- 
    Student Name: Moses Saygbe
    File Name: index.html
    Current Date: 01/31/2025
 -->
<html lang="en">
<head>
 
    <title>Chapter 10, Extend</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/styles.css">

</head>

<body>

    <div id="wrapper">
        
        <h1>Learning How to Use jQuery</h1>
    
        <article id="main">
        
                <p>I know how to create HTML pages.</p>
                <p>I know how to style webpages with CSS.</p>
                <p>I know how to add functionality to webpages with JavaScript.</p>
                <p>I understand how to use the jQuery library.</p>

                <button id="hide">Hide</button>
                <button id="show">Show</button>
        
        </article>
        
        <footer>
            <p>Student's Name: Moses Saygbe</p>
            <p>The latest version of jQuery is: </p>
            <p>Resource used to complete this assignment: </p>
        </footer>
    
    </div>
    <script src="scripts/script.js"></script>
    <script src="jquery-3.7.1.min.js"></script>
</body>
</html>

I have tried replacing the #main with ('p#main')with no luck still.

.JS code:

function remove() {
    $('#hide').click(function(){
        $('#main').hide();
    });

} 

function display() {
    $
}

When I preview the Html file, the Hide button doen’t hide the article or the p elements.

Why are escape sequences not detected in javascript? [closed]

I am trying to sanitize text for CSV export. The goal is to ensure that no CSV cells begin with certain characters (=, +, -, @, tab, carriage return). Additionally, every cell should be wrapped in double quotes, prefixed with a single quote, and all internal double quotes should be escaped.

I am using laravel, jquery and datatables.

few examples:

  • +User logged in becomes ‘+User logged in

  • “David becomes “”David

  • Larry becomes Larry

  • tDavid becomes tDavid

  • rWorking becomes rWorking

    The issue is that my regex /[rnt]/g does not remove escape sequences like tDavid, rWorking. These values still appear in the CSV instead of being sanitized. Why is this happening?

        $.ajax({
            url: url,
            method: 'get',
            dataType: 'json',
            async: false,
            data: data
        }).done(function(data) {
            result = data;

            $('.logs').DataTable({
                "data": result,
                "columns": [
                    {"mData": "event_name"},
                    {"mData": "user_fullname"},
                    {"mData": "approver_fullname"},
                    {"mData": "requester_fullname"},
                    {"mData": "instance_link"},
                    {"mData": "group_name"},
                    {"mData": "time"}
                ],
                stateSave: true,
                "dom": 'lBfrtip',
                "buttons": [
                    {
                        extend: 'csvHtml5',
                        title: 'Export',
                        text: 'Export',
                        exportOptions: {
                            format: {
                                body: function(data, row, column) {
                                    var columnNames = ["event_name", "user_fullname", "approver_fullname", "requester_fullname", "instance_link", "group_name", "time"];
                                    var columnName = columnNames[column];

                                    if (columnName === "instance_link") {
                                        return $(data).text();
                                    }
                                    if (["user_fullname", "approver_fullname", "requester_fullname"].includes(columnName)) {
                                        return sanitizeField(data);
                                    }
                                    return data;
                                }
                            }
                        }
                    }
                ]
            });
        });
        return false;
    }
    function sanitizeField(data) {
        if (data === null || data === undefined) {
            return '';
        }

        data = String(data);
        data = data.replace(/"/g, '""');
        data = data.replace(/[rnt]/g, '');

        if (/^[=+-@'<>]/.test(data)) {
            data = '${data};
        }
        if (data.includes(',')) {
            data = "${data}";
        }

        return data;
    }

Unable to update the role, even after the backend is working properly

import React, { useState } from "react";
import { auth } from "../../firebase";
import axios from "axios";

const ProfileSetup = () => {
  const [role, setRole] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    const user = auth.currentUser;

    if (user && role) {
      try {
        const response = await axios.post("http://localhost:3000/update-role", {
          uid: user.uid,
          role,
        });

        if (response.status === 200) {
          window.location.href = "/dashboard";
        } else {
          console.error("Failed to update role");
          alert("Failed to update role. Please try again.");
        }
      } catch (error) {
        console.error("Error updating role:", error);
        alert("An error occurred. Please try again.");
      }
    }
  };

  return (
    <div>
      <h1>Complete Your Profile</h1>
      <form onSubmit={handleSubmit}>
        <label>
          Select Role:
          <select value={role} onChange={(e) => setRole(e.target.value)} required>
            <option value="">Select</option>
            <option value="teacher">Teacher</option>
            <option value="student">Student</option>
          </select>
        </label>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default ProfileSetup;

Here is my basic code implementation of a project, on which I am working on role based login, where I have only provided google login, and after the login the user is profile setup where they have to select their role.
The problem is that, my backend is working properly, the role is being changed, after I send post request from postman to update-user/{user.uid}. But I am unable to update it from frontend
Just after first login, I have set the user role to null.

How do you style the ElevenLabs conv ai widget?

I’m display the element like this:

const ElevenLabsConvai = ({ agentId }: { agentId: string }) => {
  return <elevenlabs-convai agent-id={agentId}></elevenlabs-convai>;
};

But it seems to be retroactively styled by a javascript via:

But do I override the styles and changes color shape location etc?

how to change the name of visited sites in the back button list?

When you long-press or right-click on the chrome back button, it shows a list of previously visted sites. But in the application I’m developing, it shows the same name (“AppProviderTheme demo — Material UI”) for every page, even though it does go back correctly.

For example, when I navigate to localhost:3000/events and then go to a different page, I would expect the first item in the history to show that url. I’ve tried all of these combinations:

history.pushState("Events",'Events','events')
history.pushState({title:"Events"},'Events','events')
history.pushState("Events",null,'events')
history.replaceState({title:"Events"},'Events','events')
history.replaceState("Events",null,'events')
history.replaceState({title: "Events"},'Events', 'localhost:3000/events')

but none had any effect. The last one produces error
Uncaught SecurityError: Failed to execute ‘replaceState’ on ‘History’: A history state object with URL ‘localhost:3000/events’ cannot be created in a document with origin ‘http://localhost:3000’ and URL ‘http://localhost:3000/events’.

You can try them by entering them in in your browser’s development console and you’ll see what I mean.
If I can’t get it to work I’ll be forced to create my own dropdown list with the correct names. I sure don’t want to do that!

Creating new js Octokit object for Github stopped to work

I cannot run octokit for GitHub in my application. It was working for long time but stopped.
The error is

Uncaught SyntaxError: The requested module '/@octokit/webhooks-methods@^5.0.0?target=es2022' does not provide an export named 'verifyWithFallback' (at index.js:476:10)

I removed the things of the application to get the minimal application causing the error:

index.html

<script type="module">
    import myFunc from "./myFunc.js";
</script>

myFunc.js

import {Octokit, App} from "https://esm.sh/octokit";
new Octokit({
    auth: 'ghp_1234512345123451234512345'
});
const myFunc = ()=>"foo";
export default myFunc;

Before I did some things with git locally: clone, reset, push. Mayby that was the reason. I also changed the token to the new one, in GitHub and in my application. How to fix the error?

How do i recreate a React useState in VueJS?

I am trying to create a toggle funcionality to make a search bar appear and reappear by pressing on a button. I am unsure to why this code is wrong. Does anyone have any insight??

<template>
  <button
    @click="toggleSearchBar"
    v-if='!searchBarOpen"
  >
    Open Search bar
  </button>
  <div
    v-else
  >
    <input />
    <button
      @click="toggleSearchBar"
    >
    </button>
  </div>
<template>


<script setup>
import { ref } from "vue";

let searchBarOpen = ref(false);

const toggleSearchBar = () => {
  if (searchBarOpen) {
    searchBarOpen = false;
  } else {
    searchBarOpen = true;
  }
  console.log({ searchBarOpen });
};
</script>

Is there a browser method to have a smooth slide between webpages effect but load a completely new html page? (No JS script carrying over)

Ideally, I would have some css that defines an animation so that my new webpage slides in from the right of the page. However, this new page has some pretty complex javascript scripts running so when the user navigates back to the homepage the page slides out to the right again and none of the javascript remains loaded.

I also want an animation that displays both pages at the same time side by side so that when the sliding is halfway across, the homepage and application are seen at the same time.

I can make half of this animation work by loading a static view of the homepage as part of the application and then slide that out to enter the application. But I am not sure how to return to the homepage? Safari on the iphone has this feature that if you pull from the left of the page, you can see the previously loaded page slide in (but this only works if a page had already been loaded so only works for forward and backward navigation not new loading).

Maybe there is a standardized browser implementation of transitions between webpages? Or is there a way to load and unload JS modules dynamically (then I could make a single page application with transitions)?

Requests forces the host to access in HTTPS even tho its HTTP

I have an app that runs in laravel and xampp. I’m integrating Meilisearch. The sample code that is in test.html is working and i don’t encounter any issue. But i applied the code in blade of laravel, it forces the endpoint api to https but its harcoded http and im encountering error:

POST https://172.211.68.20:7700/indexes/bank_accounts/search net::ERR_SSL_PROTOCOL_ERROR

is there any trick that i can do to make this work?

Unable to resolve JavaScript File when Building with Astro

I am exploring potentially building a site using the Astro framework. As such I am working through the tutorial. Unfortunately something is not quite working right and its baffling me as to what the cause may be. I’m at the point where it tells you to insert JavaScript into a script tag in one of the components. My understanding of the documentation is the process is supposed to more or less “just work”. One creates a script tag and imports the JS file, the Astro builds it. Instead I see the following errors when building the website:

5:52:14 PM: 22:52:14 [ERROR] [vite] x Build failed in 15ms
5:52:14 PM: Could not resolve "../scripts/menu.js" from "src/pages/blog.astro?astro&type=script&index=0&lang.ts"
5:52:14 PM: file: /opt/build/repo/src/pages/blog.astro?astro&type=script&index=0&lang.ts
5:52:14 PM:   Stack trace:
5:52:14 PM:     at getRollupError (file:///opt/build/repo/node_modules/rollup/dist/es/shared/parseAst.js:396:41)
5:52:14 PM:     at ModuleLoader.handleInvalidResolvedId (file:///opt/build/repo/node_modules/rollup/dist/es/shared/node-entry.js:20216:24)
5:52:14 PM: ​
5:52:14 PM: "build.command" failed                                        
5:52:14 PM: ────────────────────────────────────────────────────────────────

The above comes from Netlify, but also occurs when I run the build command on my dev server. Here is the Astro/HTML code:

  <body>
    <Header />
  
    <h1>{pageTitle}</h1>
    <p>This is where I will post about my journey learning Astro.</p>
    
    <ul>
      <li><a href="/posts/post-1/">Post 1</a></li>
      <li><a href="/posts/post-2/">Post 2</a></li>
      <li><a href="/posts/post-3/">Post 3</a></li>
    </ul>
    
    <Footer />
  <script>
    import '../scripts/menu.js';
  </script>
  </body>

And here are the contents of menu.js:

document.querySelector('.hamburger').addEventListener('click', () => {
    document.querySelector('.nav-links').classList.toggle('expanded');
  });

When I searched Google for answers it led me to add a MIME type to the script tag which prompts Astro to not process the JavaScript. This technically allows the build to complete, but does not help as the JavaScript won’t appear in the final web page. Can anyone point me in the direction of what is going wrong?

How to add Positive and Negative array value Number in javascript or php

I need some help.
This data table image

This is part of data table

<table border="1">
    <tr>
         <th>SL No</th>
         <th><span>Closing Balance</span></th>
    </tr>
    <tr>
         <td>1</td>
         <td><span class="closing_balance">2000</span></td>
    </tr>
    <tr>
         <td>2</td>
         <td><span class="closing_balance">-300</span></td>
    </tr>
    <tr>
         <td>3</td>
         <td><span class="closing_balance">-350</span></td>
    </tr>
    <tr>
         <td>4</td>
         <td><span class="closing_balance">500</span></td>
    </tr>
    <tr>
         <td>5</td>
         <td><span class="closing_balance">-700</span></td>
    </tr>
    <tr>
         <td>6</td>
         <td><span class="closing_balance">1000</span></td>
    </tr>
    <tr>
         <td>7</td>
         <td><span id="total_closing_balance">0</span></td>
    </tr>
</table>

This is javascript code :-

function sum_closing_total(v1,v2){
    var sumval = 0;
    var nums = document.getElementsByClassName(v1);
    for(var i=0;i<nums.length;i++){
        if(nums[i].innerHTML > 0){
            sumval += parseFloat(nums[i].innerHTML);
        }
    }
    document.getElementById(v2).innerHTML = sumval;
}
sum_closing_total('closing_balance','total_closing_balance');

My result must be 2150. But result is shown 1350. Now I want to show in javascript or PHP.

In Qualtrics, what can I do to make my with javasectipt embedded HTML text exactly the same as the default text?

I try to have a table visible for multiple questions on multiple qualtrics pages one after the other. I followed guidelines here: https://community.qualtrics.com/custom-code-12/pin-instructions-to-top-of-page-as-participants-scroll-through-questions-13191

This is my javascript on the question

Qualtrics.SurveyEngine.addOnReady(function()
{
    /*Place your JavaScript here to run when the page is fully displayed*/

var base_element = document.querySelector(".QuestionOuter");
base_element.insertAdjacentHTML('afterbegin', '<div id="sticky_vid" style="position: sticky; top:0;" align="middle">');

var new_element = document.querySelector("#sticky_vid");

// Change the text below to add the element of your choice
new_element.innerHTML = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br />
&nbsp;
<br />
<table border="1" cellpadding="1" cellspacing="1" style="width:1000px;">
    <thead>
        <tr>
            <th scope="col">Some text</th>
            <th scope="col">&nbsp;Project A</th>
            <th scope="col">Project B (some more info)</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row">More text</th>
            <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit</td>
            <td>ELorem ipsum dolor sit amet, consectetur</td>
        </tr>
        <tr>
            <th scope="row">Lorep 1</th>
            <td>Lorem ipsum dolor sit amet, consectetur</td>
            <td>orem ipsum dolor sit amet, consectetur</td>
        </tr>
        <tr>
            <th scope="row">Even more text&nbsp;</th>
            <td>Required behavioral<br />
            adoption</td>
            <td>Encroaching on the land&nbsp;and rights of local communities, labour right violations</td>
        </tr>
        <tr>
            <th scope="row">Some numbers</th>
            <td>32</td>
            <td>32</td>
        </tr>
    </tbody>
</table>
<br />
We now ask you several questions on these proposed projects.<br />
&nbsp;`
;

// This is important, otherwise, the element you add will be at the back
base_element.style.zIndex = 1;
new_element.style.zIndex = 10;

});

However, the size and formatting of the text I added via JS is not the same as the text within the qualtrics question. I show this by adding the same text below without page break to show what I would have wanted instead of the stuff I got:

what I got vs what I wanted

Any idea how to fix this?

Could the custom CSS (in Look&Feel) be a problem:

.Skin .QuestionBody {
    min-width: 1300px!important;
}


.Skin .QuestionText {
    min-width: 1300px!important;
}

.Skin .SkinInner {
    min-width: 1400px!important;
}

@media only screen and (max-width: 768px) {
    .Skin .QuestionBody {
        min-width: auto !important;
    }
     .Skin .QuestionText {
        min-width: auto !important;
    }
     .Skin .SkinInner {
        min-width: auto !important;
    }
}