Why is ‘position: relative’ getting ignored for ‘tr’ elements on mobile devices?

This issue started when I realized that the slide feature on my web application was not working on mobile, but was working on desktop. I have a table full of rows that each have an “x” next to them. When an “x” is clicked, I want the row to slide left and display a delete button. When it is clicked again, I want the row to slide back to its original position. I found I could do this by simply putting overflow: hidden on the table element and using left with a transition property on each tr. The following code works for me on desktop, but not for mobile:

CSS:

table {
    border-collapse: collapse;
    margin: 25px 0;
    font-size: 0.9em;
    font-family: sans-serif;
    width: 100%;
    min-width: 400px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
    position: relative;
    overflow: hidden;
}
tbody tr {
    border-bottom: 1px solid #dddddd;
    position: relative;
    left: 0;
    transition: left 0.5s;
}
.swipe {
    left: -70px;
}

HTML/PHP:

echo "
<div class='history'>
    <h2 id='weight-history-title' align='center'>Weight History</h2>
    <table>
        <thead>
            <tr>
                <th class='th_border'>Date Weighed</th>
                <th>Weight</th>
                <td></td>
            </tr>
        </thead>
        <tbody>
";
while($row=$selectQuery->fetch_assoc()){
    $dateWeighed = htmlspecialchars(date("m/d/y", strtotime($row["date_weighed"])));
    $weight = htmlspecialchars($row["pounds"]);
    $id = htmlspecialchars($row["id"]);
    echo "
        <tr>
            <td>$dateWeighed</td>
            <td>$weight lbs</td>
            <td><img class='delete-icon' src='images/delete.png' style='cursor: pointer; width: 15px; height: 15px;'></td>
            <td class='delete'><a href='delete.php?id=$id' class='delete-button'>Delete</a></td>
        </tr>
    ";
}
echo "
    </tbody>
</table>
";

JavaScript:

for(const x of document.querySelectorAll(".delete-icon")){
    x.addEventListener("click", function(){
        let tr = x.parentElement.parentElement;
        tr.classList.toggle("swipe");
        alert("tagname: " + tr.tagName + "nclassname: " + tr.className + "nposition: " +     getComputedStyle(tr).position);
    });
}

When an “x” is clicked, the class swipe is added to its parent row which should slide 70px to the left, but on mobile, nothing happens when the “x” is clicked.

Through some research, I found out that the reason that it wasn’t working on mobile was because position: relative was not getting applied to each tr. To double check this, I made JavaScript alert the position property of each tr when clicked. On desktop, it alerts position: relative, while on mobile it alerts position: static.

Why would the position property be getting ignored on mobile?

NOTE: the code works when you preview a mobile screen through Developer Tools on desktop browser. You have to actually view the webpage on an IOS/Android device to see the issue. The table is at the bottom of the page.

Webpage URL: https://madlibsrandomgenerator.000webhostapp.com/weight/index.php

Why isn’t the ‘Add to Home Screen’ prompt showing on my PWA app for mobile devices?

I am building a PWA app. For which i require add to home screen prompt on mobile devices. But unfortunately, it is not appearing in mobile devices. I am able to see the install icon on desktop devices but not able to see popup on mobile devices.

service-worker.js

self.addEventListener("install", function (event) {
  event.waitUntil(
    caches.open("pwa").then(function (cache) {
      return cache.addAll([
        "/",
        "/templates/classic-theme/css/style.css",
        "/templates/classic-theme/js/script.js",
      ]);
    })
  );
});

self.addEventListener("fetch", function (event) {
  event.respondWith(
    caches.open("pwa").then(function (cache) {
      return cache.match(event.request).then(function (response) {
        cache.addAll([event.request.url]);

        if (response) {
          return response;
        }

        return fetch(event.request);
      });
    })
  );
});

script.js

let installEvent = null;
let installButton = document.getElementById("install");
let enableButton = document.getElementById("enable");

if (!localStorage.getItem("pwa-enabled")) {
  localStorage.setItem("pwa-enabled", true);
}
if (localStorage["pwa-enabled"]) {
  startPwa();
}

function startPwa(firstStart) {
  localStorage["pwa-enabled"] = true;

  window.addEventListener("load", () => {
    navigator.serviceWorker
      .register("/templates/classic-theme/js/service-worker.js")
      .then((registration) => {
        console.log("Service Worker is registered", registration);
        enableButton.parentNode.remove();
      })
      .catch((err) => {
        console.error("Registration failed:", err);
      });
  });

  window.addEventListener("beforeinstallprompt", (e) => {
    // e.preventDefault();
    console.log("Ready to install...");
    installEvent = e;
    document.getElementById("install").style.display = "initial";
  });

  setTimeout(cacheLinks, 500);

  function cacheLinks() {
    caches.open("pwa").then(function (cache) {
      let linksFound = [];
      document.querySelectorAll("a").forEach(function (a) {
        linksFound.push(a.href);
      });

      cache.addAll(linksFound);
    });
  }

  if (installButton) {
    installButton.addEventListener("click", function () {
      installEvent.prompt();
    });
  }
}

manifest.json

{
    "short_name": "XYZ",
    "name": "XYZ",
    "icons": [
        {
            "src": "../../../storage/logo/favicon.png",
            "type": "image/png",
            "sizes": "192x192"
        },
        {
            "src": "../../../storage/logo/favicon.png",
            "type": "image/png",
            "sizes": "144x144"
        },
        {
            "src": "../../../storage/logo/favicon.png",
            "type": "image/png",
            "sizes": "512x512"
        }
    ],
    "start_url": "https://example.com",
    "background_color": "rgba(0,189,98,0.15)",
    "display": "standalone",
    "scope": "https://example.com",
    "theme_color": "rgba(0,189,98,0.15)"
}

I tried to solve using google and stackoverflow multiple resources but non of them worked.

Recording Discord Voice Chat with discord.js results in corrupted Opus files

I am currently trying to develop a Discord bot using discord.js that records user voice chats and outputs them as Opus files. However, I’m running into issues where the outputted Opus files are corrupted and don’t contain any data.

Here’s a summary of what I’ve done so far:

  1. I’ve set up the bot to connect to a voice channel and listen to a user’s audio stream.
  2. I’m using the “@discordjs/opus” package to encode the audio data.
  3. When a user starts speaking, I create a write stream to a new Opus file and pipe the user’s audio stream into it.

With this setup, I’m able to receive data from the user’s audio stream and write it into an Opus file. I know this because I’ve set up logging at each stage of the process, and it shows that I’m receiving data and writing it into a file when a user speaks.

const { OpusEncoder } = require("@discordjs/opus");
const fs = require('fs');
const { Transform } = require("stream");
const dir = './recordings';

function transcriptionDevice(userID, voiceConn, talkingUser, time) {
    console.log('1. Start speaking event triggered');

    const opusPath = `./recordings/${userID}_${time}.opus`;
    const writeStream = fs.createWriteStream(opusPath);

    console.log('2. Created file stream for writing Opus data');

    const { receiver } = voiceConn;
    const audioStream = receiver.subscribe(userID);

    console.log('3. Subscribed to user audio stream');

    audioStream.on('data', (chunk) => {
        console.log(`Received ${chunk.length} bytes of data.`);
        // Write data directly to the file
        writeStream.write(chunk);
        console.log('4. Wrote data to file');
    });

    audioStream.on('end', () => {
        console.log("5. Audio stream ended");
        // End the write stream when the audio stream ends
        writeStream.end();
    });

    writeStream.on("finish", () => {
        console.log("6. File write finished");
    });

    audioStream.on('error', (err) => {
        console.error('7. An error occurred:', err);
    });
}

This is the most recent attempt I have tried, I get all the console logs, and I get the opus file, but again when I open it in VLC or try to convert it to wav with ffmpeg it just reads as a “corrupt” file it opens the program and has 0 data, can’t hit play or anything.

I also recently checked my bots permission and I am 90% sure I have the ones I need connect, speak, voice activity

MongooseError: Model.findOneAndUpdate() no longer accepts a callback

I’ve encountered a problem while setting up mongoose.

My code

`export const getOne = (req, res) => {
try {
const postId = req.params.id

    PostModel.findOneAndUpdate(
        {
            _id: postId,
        },
        {
            $inc: { viewsCount: 1 },
        },
        {
            returnDocument: 'after',
        },
        (err, doc) => {
            if (err) {
                console.log(error)
                return res.status(500).json({ message: "cant return post" })
            }

            if (!doc) {
                return res.status(404).json({
                    message: "post not found"
                })
            }

            res.json(doc)
        },
    )
} catch (error) {
    console.log(error)
    res.status(500).json({ message: "cant retunr post" })
}

}`

error

MongooseError: Model.findOneAndUpdate() no longer accepts a callback
at Function.Model.findOneAndUpdate (C:UsersKousDesktopFirst-Full-Stacknode_modulesmongooselibmodel.js:2398:11)
at getOne (file:///C:/Users/Kous/Desktop/First-Full-Stack/controllers/PostController.js:40:13)
at Layer.handle [as handle_request] (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterroute.js:144:13)
at Route.dispatch (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterroute.js:114:3)
at Layer.handle [as handle_request] (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterindex.js:284:15
at param (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterindex.js:365:14)
at param (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterindex.js:376:14)
at Function.process_params (C:UsersKousDesktopFirst-Full-Stacknode_modulesexpresslibrouterindex.js:421:3)

How to use promise return properly

I am trying to call two function from another function so How I can I get returns back properly

// s3 manage file 
const imageCopyAndDelete = async (oldName, newName, area) => {
   await s3.copyObject(copyparams).promise();
   await s3.deleteObject(paramsDelete).promise();
}

//api file 
exports.BSComponentUpdadeCompoName = async (req, res, next) => {
        let response = await imageCopyAndDelete(oldName, newName, 'folder');
        // further steps

});

Trying with promise but I dont understand how to call multiple function

// return new Promise(resolve => {
//     s3.copyObject(copyparams, (err, data) => {
//         if (err) {
//             resolve(err);
//         }
//         resolve(data);
//     });
// });

Unzipping Large File and Saving to MongoDB

I am trying to download a very large zip file, unzip and pipe the files to google cloud and then get each file from the bucket and download it to mongodb so there is no memory over load. I think I am doing everything right but I am still getting this error

<— Last few GCs —>

[8143:0x150040000] 100257 ms: Scavenge 6856.9 (7026.4) -> 6850.6 (7030.9) MB, 22.5 / 0.4 ms (average mu = 0.138, current mu = 0.113) allocation failure;
[8143:0x150040000] 100331 ms: Scavenge 6861.2 (7030.9) -> 6855.3 (7036.2) MB, 22.5 / 0.4 ms (average mu = 0.138, current mu = 0.113) allocation failure;
[8143:0x150040000] 100522 ms: Scavenge 6865.2 (7036.2) -> 6859.7 (7041.2) MB, 17.8 / 0.2 ms (average mu = 0.138, current mu = 0.113) external memory pressure;

<— JS stacktrace —>

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed – JavaScript heap out of memory

Here is the code I have so far

import axios from 'axios'
import AdmZip = require('adm-zip');
import { Storage } from '@google-cloud/storage'
import mongoose from 'mongoose'
import { Readable } from 'stream'

const storage = new Storage()
const bucketName = process.env.BUCKET_NAME

// Fetch company filings data
async function fetchCompanyFilingsData() {
    const response = await axios.get(
        'https://www.sec.gov/Archives/edgar/daily-index/bulkdata/submissions.zip',
        { responseType: 'arraybuffer' }
    )
    if (!response.data) {
        throw new Error('No data received from URL.')
    }
    return response.data
}

// Unzip and upload data to Google Cloud Storage
async function unzipAndUploadData(buffer: Buffer) {
    const zip = new AdmZip(buffer)
    const files = zip.getEntries().filter((file) => /.json$/i.test(file.name))

    if (!files.length) {
        throw new Error('No JSON files found in ZIP archive.')
    }

    for (const file of files) {
        const bucket = storage.bucket(bucketName)
        const blob = bucket.file(file.name)

        const blobStream = blob.createWriteStream()

        blobStream.on('error', (err) => {
            console.error(err)
        })

        blobStream.on('finish', () => {
            console.log(`Uploaded ${file.name} to Google Cloud Storage`)
            blobStream.end() // Close the writable stream
        })

        // Convert content (which is a Buffer) to a Stream
        const readableStream = new Readable()
        readableStream.push(file.getData())
        readableStream.push(null)

        // Pipe the stream to blobStream
        readableStream.pipe(blobStream)
    }
}

// Parse JSON files and save data to MongoDB
async function saveDataToMongoDB(db) {
    const filingsCollection = mongoose.connection.db.collection('edgar-filings')
    const bucket = storage.bucket(bucketName)
    const [files] = await bucket.getFiles()

    for (const file of files) {
        if (file.name.endsWith('.json')) {
            const content = file.createReadStream() // Read the file as a readable stream

            let data = ''
            content.on('data', (chunk) => {
                data += chunk.toString()
            })

            content.on('end', async () => {
                const jsonData = JSON.parse(data)

                const existingFiling = await filingsCollection.findOne({ cik: jsonData.cik })
                if (!existingFiling) {
                    const result = await filingsCollection.insertOne(jsonData)
                    console.log('Inserted filing:', result)
                } else {
                    console.log('Filing already exists:', jsonData)
                }
            })
        }
    }
}

export async function processCompanyFilingsData(db): Promise<void> {
    try {
        const buffer = await fetchCompanyFilingsData()
        await unzipAndUploadData(buffer)

        await mongoose.connect(process.env.MONGODB_URI) // Replace with your MongoDB connection string
        await saveDataToMongoDB(db)
        await mongoose.disconnect()

        console.log('Data saved to MongoDB')
    } catch (error) {
        console.error(error)
    }
}

`export const config` Please change `runtime` property to segment export config

I am basically trying to create upload api route in my application.

/admin/upload

and when I try to console.log(req.file), I keeping I get undefined.

It seems that this:

export const config = {
    api: {
        bodyParser: false,
    }
}

Is not supported while using app router, I can’t figure any other ways.

import { createEdgeRouter } from "next-connect";
import { NextResponse } from "next/server";
import multer from "multer";

export const config = {
    api: {
        bodyParser: false,
    }
}

const router = createEdgeRouter();

const upload = multer({
    storage: multer.diskStorage({
        destination: './public/uploads',
        filename: (req, file, cb) => cb(null, file.originalname),
    }),
});

const file = upload.single('file');
router
    .use(file)
    .post((req) => {
        // console.log(req.pageType);
        console.log(req.pageType);
        return NextResponse.json({ 'message': 'Hi mom' })
    });

export async function POST(req, ctx) {
    return NextResponse.json("Hi")
}

Here is my backend code.

When I checked docs at the page mentioned, I couldn’t find anything helpful.
Any idea how to fix this?

Please note I am using app router not pages router.

React dev strict mode on load animation using useEffect with empty dependency array triggered twice

I have the following code to load the last state from a connect 4 game and recreate it using a fancy animation:

useEffect(() => {
    const history = historyFromStateURL();

    (async () => {
        for (const colIndex of history) {
            await sleep(100);

            dispatch({
                type: 'CLICK',
                colIndex,
                isReplay: true,
            });
        }
    })();
}, []);

The problem is, that the code is not side effect free, if the effect is run twice, twice as many clicks will be dispatched and the state of the component will be different. Since I am using React strict mode, thats exactly what happens.

In my opinion the code should be fine, since the useEffect hook can only ever run once per component, but it seems react disagrees.

Any ideas how I could change the code to make it work in strict dev mode too?

What can I do to fix the jerky movement of my swipe animation with Vue 3 and Hammer.js?

I have been trying to achieve this effect for days and I just don’t understand what I might be doing wrong or what is coming into play when I do this type of animation. All I want is to detect a click or a touchevent from a mobile and have the box move up or down. I have looked up an example project and literally copied what it does, however, my box does not move right, it moves in jumps and incorrectly not smoothly at all.

This is my Vue component:

<script lang="ts">
import Hammer from 'hammerjs';
import Vue from 'vue';

export default {
    data() {
        return {
            offset: 0,
            threshold: 400,
            isDragging: false,
        };
    },
    mounted() {
        this.setupHammer();
    },
    methods: {
        setupHammer() {
            const hammertime = new Hammer.Manager(this.$refs.post);

            hammertime.add(
                new Hammer.Pan({
                    threshold: this.threshold,
                    pointers: 0,
                    direction: Hammer.DIRECTION_VERTICAL,
                })
            );

            hammertime.on('pan', (event) => {
                this.offset = event.deltaY / this.$refs.post.clientHeight;
                console.log(this.offset);
            });

            hammertime.on('panstart', (event) => {
                this.isDragging =
                    event.offsetDirection === Hammer.DIRECTION_DOWN ||
                    event.offsetDirection === Hammer.DIRECTION_UP;
            });

            hammertime.on('panend', (event) => {
                this.isDragging = false;

                if (event.deltaY > 200 || event.velocityY > 0.4) {
                    this.offset = 1;
                } else {
                    this.offset = 0;
                }
            });
        },
    },
};
</script>

<template>
    <div
            class="uppBox scrollableUppbox uppBox--pink post"
            ref="post"
            :style="{ transform: `translate3d(0, ${offset * 100}%, 0)` }"
    >
        <div class="post__iconBox">
            <i class="material-icons">pause</i>
        </div>
        <div class="post__authorData">
            <div>photo</div>
            <h1>ExampleUser</h1>
        </div>
        <div class="post__content">
            Content
        </div>
    </div>
</template>

This is the post CSS (the other ones are only colors and shadows)

.post
  position: relative
  flex-direction: column
  font-family: Inter, "Inter Semi Bold", sans-serif
  font-weight: 400
  padding: .5em 1.2em
  height: 100%
  transition: 0.3s ease-in-out 

This is the behaviour of my box:

https://imgur.com/vF85N1L

And this is the smoothness I want (from this project https://github.com/scriptcoded/vue-3-card-swiper/tree/main):

https://imgur.com/CQHQvDS

I tried to change transform: translate3d(0, ${offset * 100}%, 0) to only translateY(offset), but same happens. I tried to change the offset variable to setup or tried to calculate the offset directly, but it is still not smooth.

Re-fetch tag href with JavaScript

I currently have a link tag (<link rel="stylesheet" href="https://example.com/example.css">) which has content that might be changing quite frequently.

I want to force re-fetch the link’s href so it uses the new content without reloading the entire page.

I’ve tried changing the link’s href to end with ?[random string] to make it re-fetch but that’s not very clean at all and it might cause issues if I want to do something more complex.

I can’t figure out any other way of achieving this. Any ideas are greatly appreciated!

How can I create a modal with a loop object in JavaScript and Bootstrap?

hy, i have school project and i want to create modal,

i create an array empty for taking information, and i write it with an loop for taking information of my artist

`<body onload=”runScripts()”>

ARTISTES

var artists = [];

function runScripts() {
  displayArtists();
}

function displayArtists() {
  artists.forEach(artist => {
    console.log(artist);
  });


}

THIS IS THE BIG ARTIST IN THE WORLD

{{range .}}

artists.push({
  "id": "{{ .ID }}",
  "image": "{{ .Image }}",
  "name": "{{ .Name }}",
  "Members": "{{ .Members }}",
  "firstAlbum": "{{ .FirstAlbum }}",
  "creationDate": "{{ .CreationDate }}",
  "relations": "{{ .Getrelation }}"
  
  
});

{{end}}`

i have this output : enter image description here

and i want to create modal with this. for this i try many attemps,

i search on stack but i don’t understand the code, he his the code i see but dos’ent work : i have try many many, this this is my history Lmao the list is long 🙁 thank you.

Is there any global mouse listener for the web?

I am trying to move an electron application to the web. But the electron app tracks mouse clicks and plays it to the user. I want that same functionality on the web.

I am currently using the following library to do this.
https://github.com/wilix-team/iohook

Is there any way to do global tracking for a web app?

I am using React. I need basically need to store on what part of the screen a user pressed. So it must work when the user clicks on any other app and not just the browser

I am basically tracking clicks in a screen recorder. So I can highlight them in the video. Using recordRtc for the recording.

Is this possible to do in any way?

Troubleshooting: Inconsistent Action Alignment with ID in Laravel Database

I’m creating a table to do validation, pending and reject, based on existing data in the database. but as I attached in the picture the button for validating is on the right. that should align with the data. how to solve this problem? because to be honest I have been confused for 2 days to solve this problem

        @foreach($projects as $project)
    <td>
                @if ($project->status == '0')
                    <button onClick="toggleStatus('{{$project->id}}')">Verifikasi</button>
                @elseif ($project->status == '1')
                    <button onClick="toggleStatus('{{$project->id}}')">Unverifikasi</button>
                @endif
                @if ($project->pending == '0')
                    <button onClick="pending('{{$project->id}}')">Pending</button>
                @elseif ($project->pending == '1')
                    <button onClick="pending('{{$project->id}}')">Unpending</button>
                @endif
                @if ($project->invalid == '0')
                    <button onClick="invalid('{{$project->id}}')">Invalid</button>
                @elseif ($project->invalid == '1')
                    <button onClick="invalid('{{$project->id}}')">Unvalid</button>
                @endif
    </td>
        @endforeach

and the javascript is like this

   <script>
function toggleStatus(project_id) {
    fetch("{{ route('projects.toggle') }}?project_id=" + project_id)
        .then(response => response.json())
        .then(response => {
            document.querySelector("#project-status-" + project_id).innerHTML = response.status;
     })
}
function pending(project_id) {
    fetch("{{ route('projects.pending') }}?project_id=" + project_id)
        .then(response => response.json())
        .then(response => {
            document.querySelector("#project-pending-" + project_id).innerHTML = response.pending;
     })
}
function invalid(project_id) {
    fetch("{{ route('projects.invalid') }}?project_id=" + project_id)
        .then(response => response.json())
        .then(response => {
            document.querySelector("#project-invalid-" + project_id).innerHTML = response.invalid;
     })
}
</script>

enter image description here

How to change display of a project with javascript

How do I add a function where in an html project I can change the language or the text on a website when I choose an option using javascript? For example if I were to choose french from the option in the image the text on the website would change to french enter image description here

Also how do I change the background color of a website and color of text on a website when i click on a button? Like a button to change the website from light mode to dark mode and vice versa?

how to call chrome default translator?

hi my English is not good. sorry.
i want call chrome default translator for my javascript:

function translateHtml()
{
 document.documentElement.setAttribute('lang','fa')
 document.documentElement.classList.add('translated-rtl')
  //call google translate this page
}
<a onclick="translateHtml">translate</a>

enter image description here