reloading page after the alert button

After approve button the alert message will appear and has 2 option button “ok” and “cancel”. after clicking ok the page will reload, the problem is I can’t do multiple approval because after clicking the alert ok button the page will reload.

I tried the onclick function but it still reloading after i click the approve button, also tried to remove the alert (data-confirm) but still reload the page.

I’m using these line of code:

<button type="submit" name="status" value="2" class="btn btn-success btn-sm m-b-0-0 waves-effect waves-light" data-confirm="Are you sure you want to approve this leave application?"  title="Approve">
    <i class="fa fa-check"></i>
</button>

This is the output of button:

image of button output

How can I multiple approve without appearing of alert but it still record the data?

after i click the check button the pending must change into aprrove, how to do that without reloading or refreching the page?

enter image description here

these is the whole code of the image

How to detect the “first render” of a progressively loaded image in JavaScript?

Some file formats like jpeg and webp allow “progressive loading” where the file is encoded in a way such that a lower resolution version of the image can be rendered before the entire file has finished loading.

However, the “onload” event will still only trigger once the image has fully loaded in its highest resolution state which begs the question of what to do if you are interested in the moment the image appear on the screen instead.

My question is if I can detect when the first lower resolution version has loaded and can be rendered?

something like:

// Hypothetical event
image.onreadytorender = () => placeholder.hide() && image.show();  

My usecase is that I want to remove and replace a LQIP (low quality image placeholder) with the real image as soon as it has loaded enough to render its low resolution version instead of having to wait for the fully loaded version which is what onload would do.

// This would not leverage the advantages of progressive loading
image.onload = () => placeholder.hide() && image.show()

Typically, all tutorials I have found on loading images says to use JS and the onload event to replace the placeholder with the real image. However, this does not make any sense considering how modern file formats like webp and avif work. One of their greatest advantages is that they can be rendered before it is fully loaded and onload is triggered. So is there a way to detect when the first paint of the image can happen? Or how do I leverage the advantages of progressive loading while also using a LQIP?

I have considered just loading the image on top of the LQIP without any JS, however, this would not work for images with transparency because the LQIP would be blurred causing it to overflow beneath the full image if it is not removed. It also would not trigger any fade in animations.

AWS amplify shows a white screen just after successful deployment

The whole code has been seen working properly, the deployment has been done successfully. the front and backend deployment works fine, but when I tried to access the deployed api domain “https://main.d3td3qxr7rh3ge.amplifyapp.com”, it shows white screen, even everything works fine

I have attached the file names of my project. don’t know which file modification can rectify the error. enter image description hereenter image description here.

I tried redeploying the code with the latest build but still showed the same error.

other than that I have no idea what to do and how to rectify or which file should I access.

translate3d virtualization on scroll?

I saw some websites using CSS translate3d to virtualize list and table by manipulating viewport, such as AirTable. I googled translate3d virtualized and translate3d virtualized react, but I didn’t find useful websites. How is it called this approach? Could you provide some useful websites about this?

Also, what are the pros and cons of this approach compared to the approach of traditional approach such as react-window?

MongooseError: Operation `users.findOne()`

I was creating a movie website and I was setting up a login I tried to register using POST through Insomnia which resulted in an error saying “MongooseError: Operation users.findOne() buffering timed out after 10000ms”. I tried to solve as much as possible but so far not able to fix this issue. Can anyone help me fix the issue?

import userModel from "../model/userModel.js";

export default class AuthController{
  static async sendToken(user, statusCode, res){
    const token = user.getSignedToken(res);
    res.status(statusCode).json({
        success: true,
        token,
    });
  }

  static async registerController(req, res, next) {
    try {
      const { username, email, password } = req.body;
      const exisitingEmail = await userModel.findOne({ email });
      if (exisitingEmail) {
        return next(new errorResponse("Email is already register", 500));
      }
      const user = await userModel.create({ username, email, password });
      this.sendToken(user, 201, res);
    } catch (error) {
      console.log(error);
      next(error);
    }
  }

  static async loginController(req, res, next){
    try {
      const { username, password } = req.body;
      if (!username || !password) {
        return next(new errorResponse("Please provide email or password"));
      }
      const user = await userModel.findOne({ username });
      if (!user) {
        return next(new errorResponse("Invalid Creditial", 401));
      }
      const isMatch = await user.matchPassword(password);
      if (!isMatch) {
        return next(new errorResponse("Invalid Creditial", 401));
      }
      this.sendToken(user, 200, res);
    } catch (error) {
      console.log(error);
      next(error);
    }
  }

  static async logoutController(req, res, ){
    res.clearCookie('refreshToken');
    return res.status(200).json({
        success:true,
        message:'Logout Successfully',
    });
  }
}

Nodejs and Handlebars, parsing a string as an array

I am developing a website for a project. The main function of this website is to allow registered users to create, edit, and share wish lists that they create. This website is made using nodejs, handlebars as a view engine, and html/js for code. It uses mysql to log user info and list items. My list creation screen allows possibly infinite inputs by creating a new input field on the press of a button. It works as follows:

 addBtn.addEventListener('click', function () {
        
        const item_contianer = document.createElement('div');
        item_contianer.className = 'item-container';

        const item = document.createElement('input');
        item.type = 'text';
        item.id = 'item';
        item.name = 'item';
        item.placeholder = 'Insert Item Here';
        item.required = 'true';

        const removeBtn = document.createElement('button');
        removeBtn.id = 'remove';
        removeBtn.innerHTML = 'X';

        list.appendChild(item_contianer);
        item_contianer.appendChild(item);
        item_contianer.appendChild(removeBtn);

        removeBtn.addEventListener('click', function () {
            this.parentElement.remove();
        });

    });

When I save this info in my database, it is saved as an string in the format of an array ([“Item 1″,”Item 2″,”Item 3”] by the following code:

exports.create = async (req, res) => {
    const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);
    const listName = req.body.list_name;
    **const listItems = JSON.stringify(req.body.item);**
    
    db.query('INSERT INTO userlists SET ?', {id: decoded.id, listName: listName, listItems: listItems}, (err, results) => {
            if(err) {
                console.log(err);
            } else {
                return res.status(200).redirect('../view');
            }
    });
}

To access this info I read it from the table and send a JSON object to the page:

exports.view = async (req, res, next) => {
    if(req.cookies.jwt) {
        try {
            const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);

            db.query('SELECT * FROM userlists WHERE id = ?', [decoded.id], (err, results) => {
                if(!results) {
                    return next();
                }
                req.lists = Object.values(JSON.parse(JSON.stringify(results)));
                return next();
            });
        } catch (error) {
            console.log(error);
            return next();
        }
    } else {
        next();
    }
}

When I try to read this object I want to print the List name and then print each item in the string array on a seperate line as follows:

<div class="container">
        <div class="title">
            <h1>View a List</h1>
    </div>
    {{#each lists}}
        <div>
            <h3>{{listName}}</h3>
            {{#each listItems}}
                {{this}}
            {{/each}}
        </div>
    {{/each}}
    </div>

I have tried converting ‘listItems’ into a JSON object with JSON.parse(JSON.stringify(listItems)) but it returns a parser error: Expecting ‘ID’, got ‘INVALID’.
I’ve also tried just to parse it but it returs the same.
I am relatively new to most of this, especially handlebars so any help will be greatly appreciated.

Script JS avec WordPress et wp event manager

Bonsoir,
J’ai un site wordpress sur lequel je gère des événements avec le plugin WP event manager
J’ai créer un modèle dans le thème builder qui s’applique pour tout les évènements dans ce modèle il y a entre autre une section photo qui affiche les photos de l’événement. J’aimerai que cette section ne s’affiche que lorsqu’un événement est terminé et donc qu’elle n’apparaisse pas sur la page des événements qui sont à venir.
J’ai essayé d’écrire un script en js à l’aide de l’ia pour arriver à mes fins mais ça ne fonctionne pas. Je pense que c’est faisable car en plus le plugin wp event manager a un slut pour les événements expiré
Si quelqu’un pourrait me donner quelques pistes ça m’aiderai beaucoup

J’ai essayé de créer un script JS à l’aide de l’ia pour comparer la date de fin de l’événement avec celle du jour afin de désactiver l’affichage de ma section sur laquelle j’ai mis un id photo mais cela n’a rien donné

How to Integrated A QR Code Scanner In a Google Sheet Web App Without a 3rd Party Application and Auto Populate the Scan Result to a Place Holder

I am trying to create a Web App that has search capability. Rather than manually typing the keywords to the search place holder, the search keywords will be coming from another Google Sheet that should auto populate to the search parameter place holder via QR code. For that reason, I need to integrate a QR Code scanner to the Web App itself. My code works if you dragged the QR Code to the scanner place holder, but the it is not working when you scan the QR Code directly using the integrated scanner. I am an aspiring coder and has limited knowledge about programming languages.

HTML Code

<html>
<head>
    <script src="https://unpkg.com/html5-qrcode"></script>
</head>
<body>
    <input type="text" id="searchInput" placeholder="Enter search parameter">
    <div id="qr-reader"></div>
    <script>
        function handleQRCode(decodedText) {
            document.getElementById('searchInput').value = decodedText;
        }

        const html5QrcodeScanner = new Html5QrcodeScanner("qr-reader", {
            fps: 10,
            qrbox: 250,
        });

        html5QrcodeScanner.render(handleQRCode);
    </script>
</body>
</html>

JS Code

function doGet() {
    return HtmlService.createHtmlOutputFromFile('Page')
        .setTitle('QR Code Scanner Web App');
}

function getQRCode(decodedText) {
    Logger.log('Decoded QR code text: ' + decodedText);
}

Mongoose Creating models and collecting them all in one generalized model

I have several models:
PhoneModel, HeadphonesModel, Notebookmodel

After creating these models, I need to put them all into one generalized ProductModel model. I need to make sure that when searching in ProductModel.find(), I get a list of all models with their fields, similarly for a single search ProductModel.find({id})

// HeadphonesModel //

import mongoose, { Schema, model } from 'mongoose'

const PhoneSchema = new Schema({
    name: { type: String, required: true },
    type: {
        type: mongoose.Schema.ObjectId,
        ref: 'Type',
    },
})

export default model('Phone', PhoneSchema)
// PhoneModel //

import mongoose, { Schema, model } from 'mongoose'

const Headphones = new Schema({
    name: { type: String, required: true },
    type: {
        type: mongoose.Schema.ObjectId,
        ref: 'Type',
    },
})

export default model('Headphones', HeadphonesSchema)

import mongoose, { Schema, model } from 'mongoose'

const NotebookSchema = new Schema({
    name: { type: String, required: true },
    type: {
        type: mongoose.Schema.ObjectId,
        ref: 'Type',
    },
})

export default model('Notebook', NotebookSchema)

import { Schema, model } from 'mongoose'

const ProductsSchema = new Schema({
    // I don't know how to describe this model correctly
})

export default model('Products', ProductsSchema)

Displaying main content after loading with loading GIF

I’m trying to display a loading GIF while my web page is loading, and then hide the loading GIF and display the main content once the page has finished loading. I’ve tried using JavaScript to achieve this, but I’m encountering an issue where the main content doesn’t display after the loading GIF disappears. Here’s my code:

landingpage.js:

window.addEventListener("load", function () {
    var loading = document.getElementById("loading");
    loading.style.display = "none";

    var mainContent = document.querySelector(".l-main");
    mainContent.style.display = "block"; // This line doesn't seem to work
});

landingPage.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Head content -->
</head>
<body>
    <div id="loading">
        <!-- Loading GIF content -->
    </div>
    <main class="l-main">
        <!-- Main content -->
    </main>
    <script src="landingpage.js"></script>
</body>
</html>

I expect the main content to be displayed after the loading GIF disappears, but it doesn’t seem to be working. Can someone please help me identify what I’m doing wrong or suggest a better approach to achieve this? Thank you!

Edit:

How i hidden the .l-main:

<style>
        /* Styles for the loading screen */
        #loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgb(0, 0, 0);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* Hide the main content initially */
        .l-main {
            display: none;
        }
        .l-header{
            display: none;
        }
    </style>

Multiple independent line marks

Using Observable Plot v0.6, I’d like to add more than one line mark with independent data to my plot and have the legend generated automatically. Using d3.js v7 to change the HTML body after running b = d3.select('body'):

b.html('').append('li').node().append(Plot.plot({
color: {legend:true},
marks: [
Plot.lineY({length:6, title:"CH1"}, {y:[1,4,2,5,3,6],x:[1,2,3,4,5,6]}),
Plot.lineY({length:4, title:"CH2"}, {y:[2,4,1,5],x:[1,2.5,4.5,6]}),
]}))

But that produces neither a legend nor different colours.

I can directly control the colours like so:

b.html('').append('li').node().append(Plot.plot({
color: {legend:true},
marks: [
Plot.lineY({length:6}, {y:[1,4,2,5,3,6],x:[1,2,3,4,5,6], stroke:"red"}),
Plot.lineY({length:4}, {y:[2,4,1,5],x:[1,2.5,4.5,6], stroke:"blue"}),
]}))

but there still is no legend.

Most examples I found assume all lines to use the same x points, but this is not true in my case. Also for my application I’d like to have 1000s of points, so a compact representation (like in the example above) would probably preferable over something like

{
  {x:1, y:1, ch:1},
  {x:2, y:4, ch:1},
  {x:3, y:2, ch:1},
  {x:4, y:5, ch:1},
  {x:5, y:3, ch:1},
  {x:6, y:6, ch:1},
  {x:1, y:2, ch:2},
  {x:2.5, y:4, ch:2},
  {x:4.5, y:1, ch:2},
  {x:6, y:5, ch:2}
}

but I’m open to re-arranging my data if really necessary.

My Antd Input with addonbefore prop has styling issues

I am trying to create an input using antd. If i remove the addonBefore prop, the style works perfectly well. Once i use the addonBefore prop, the input has a fixed square like style. Please what am i doing wrong?. My code is below, ps i am using Tailwind.

<Input
    className="h-12 rounded-full mt-1.5 border-lg-grey-100 pl-4"
    style={{
     paddingBottom: "10px",
     paddingTop: "10px",
     }}
     addonBefore={countries}
     placeholder={code}
     // variant="borderless"
     id="phone"
     onChange={handleChange}
 />

The addon before component

const countries = (
    <Select
      onChange={(value) => {
        setCode(value);
      }}
      defaultValue="+234"
    >
      <Option value="+234">{<Ng />}</Option>
      <Option value="+20">{<Gh />}</Option>
      <Option value="+20e">{<Eg />}</Option>
    </Select>
  );

You can check here for the image.

I am expecting the input component to follow the Tailwind classes i gave

Media3 API JavaScript Android

How would one go about using MediaSession (part of the Media3 API) in a Nativescript android app? Currently, all the examples I’ve seen are in Kotlin or Java.

I’d like to convert this to either JavaScript or TypeScript.

override fun onCreate() {
  super.onCreate()

  val likeButton = CommandButton.Builder()
    .setDisplayName("Like")
    .setIconResId(R.drawable.like_icon)
    .setSessionCommand(SessionCommand(SessionCommand.COMMAND_CODE_SESSION_SET_RATING))
    .build()
  val favoriteButton = CommandButton.Builder()
    .setDisplayName("Save to favorites")
    .setIconResId(R.drawable.favorite_icon)
    .setSessionCommand(SessionCommand(SAVE_TO_FAVORITES, Bundle()))
    .build()

  session =
    MediaSession.Builder(this, player)
      .setCallback(CustomMediaSessionCallback())
      .setCustomLayout(ImmutableList.of(likeButton, favoriteButton))
      .build()
}

I can’t get data from props

I populate data prop from App.js file and send it to CarDetails page.

App.js (I console data here and it shows me an array of objects)

const [data, setData] = useState<CarType[]>([])
     <Route exact path="/carDetails/:id">
        <CarDetails data={data} />
     </Route>

In CarDetails.js it’s undefined after FIND () method. as a prop it’s showing an array of objects

const [item, setItem] = useState<CarType>({} as CarType)

  const { id } = useParams<{ id: string }>()
  useEffect(() => {
    const found = data.find((item) => item.id === id)
    if (found) {
      setItem(found)
    }
  
  }, [data, id])

so when I console log const found it’s undefined.