How do I get multiple data-attributes from a single option select assigned to different javascript variables?

I am trying to assign 2 different javascript variable values from multiple data-attributions in a dropdown menu. One value is working just fine, the other keeps returning null. Any suggestions would be greatly appreciated!

Example of an option line from html form:

<select onchange="calculateNPF()" id="yourCamera" name="yourCamera" class="form-control">

<option value="79" data-sensor-width="36" data-sensor-height="24" data-cropFactor="1" data-pixelPitch="6.6" data-resolution="20.1">Canon EOS R6</option>
let yourCameraPixelSize = document.getElementById('yourCamera');
let pixelSize = yourCameraPixelSize.getAttribute('data-pixelPitch');
let yourCameraSensorSize = document.getElementById('yourCamera');
let sensorSize = yourCameraSensorSize.getAttribute('data-cropFactor');

In the above code “pixelSize” is working properly whereas sensorSize returns null

Set pdf name using EMBED and URL.createObjectURL (not for download)

DISCLAIMER for duplicate markers: this question is NOT about downloading a file. Please read the question before marking it as a duplicate.

I’m using embed to render a PDF file inside an HTML document. If I proceed as follows:

const embed = document.createElement("EMBED");

const url = "../pdf_files/test.pdf";
embed.src = url;

const content = document.getElementById("content");
content.innerHTML = "";
content.appendChild(embed);

the browser pdf viewer renders the document using the filename, as highlighted in the image below:

enter image description here

But if I use Blob/File/URL.createObjectURL, the pdf viewer does not use the file name:

const embed = document.createElement("EMBED");
const url = "../pdf_files/test.pdf";

const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());

const blob = new Blob([existingPdfBytes], {
    type: 'application/pdf'
});
const file = new File([blob], "hello.pdf", {"type": "application/pdf"});

embed.src = window.URL.createObjectURL(file)

const content = document.getElementById("content");
content.innerHTML = "";
content.appendChild(embed);

enter image description here

Is there a way to set this file name in order to display it properly on the pdf viewer using URL.createObjectURL?

How to make the text stay inside the div

I need to make the big text to stay within the div and if it like touches the side of the div, it goes to the next line and at the end of this big text must be a cross

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ToDo List</title>
    <link
      rel="apple-touch-icon"
      sizes="180x180"
      href="/favicon/apple-touch-icon.png"
    />
    <link
      rel="icon"
      type="image/png"
      sizes="32x32"
      href="/favicon/favicon-32x32.png"
    />
    <link
      rel="icon"
      type="image/png"
      sizes="16x16"
      href="/favicon/favicon-16x16.png"
    />
  </head>
  <body>
    <div id="container">
      <div class="darkMode">
        <label class="inline-flex items-center cursor-pointer">
          <input
            type="checkbox"
            id="toggleDarkMode"
            value=""
            class="sr-only peer"
            autocomplete="off"
          />
          <div
            class="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-indigo-600"
          ></div>
          <span
            class="darkModeText ms-3 text-base font-medium text-gray-900 dark:text-gray-300"
            >Dark Mode</span
          >
        </label>
      </div>
      <div id="app">
        <h1 class="app-title">ToDo List:</h1>
        <div class="app-container">
          <div class="app-inner">
            <input
              type="text"
              class="input-text"
              id="input-box"
              placeholder="Save your note:"
            />
            <button class="primary-btn" id="btnCreateList">Add</button>
          </div>
        </div>
        <div class="list-outer">
          <div id="list-container"></div>
        </div>
      </div>
    </div>
    <script type="module" src="./src/js/main.js"></script>
  </body>
</html>

import { list } from "postcss";
import "../css/style.css";
import { darkModeHandle } from "./utils";

darkModeHandle();

const btnFunc = document.getElementById("btnCreateList");

btnFunc.addEventListener("click", () => {
  let inputText = document.getElementById("input-box").value;

  if (inputText.trim() === "") {
    alert("Write a text");
    return;
  } else {
    const checkBoxContainer = document.getElementById("list-container");
    const checkBox = document.createElement("input");
    checkBox.type = "checkbox";
    checkBox.classList.add("checkbox-auth");

    const label = document.createElement("label");
    label.textContent = inputText;
    label.classList.add("checkbox-auth-text");

    checkBox.addEventListener("change", () => {
      if (checkBox.checked) {
        label.classList.add("checked");
      } else {
        label.classList.remove("checked");
      }
    });

    const deleteBtn = document.createElement("button");
    deleteBtn.textContent = "❌";
    deleteBtn.classList.add("delete-btn");

    deleteBtn.addEventListener("click", () => {
      checkBox.remove();
      label.remove();
      deleteBtn.remove();
      br.remove();
    });

    const br = document.createElement("br");

    checkBoxContainer.append(checkBox);
    checkBoxContainer.append(label);
    checkBoxContainer.append(deleteBtn);
    checkBoxContainer.append(br);

    document.getElementById("input-box").value = "";
  }
});

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  @font-face {
    font-family: Monserat;
    font-weight: 700;
    font-style: normal;
    src: url("../../public/fonts/monserat/AzeretMono[wght].ttf")
      format("opentype");
  }
  html {
    font-family: Monserat, sistem-ui, sans-serif;
  }
}

@layer components {
  #container {
    @apply h-screen dark:text-white dark:bg-zinc-800 overflow-x-hidden overflow-y-auto;
  }
  #app {
    @apply flex flex-col items-center mt-20;
  }
  #list-container {
    @apply w-full mt-3 border-2 p-2 bg-zinc-700 rounded-md;
  }
  .list-outer {
    @apply w-6/12;
  }
  .checkbox-auth-text {
    @apply text-2xl overflow-hidden overflow-ellipsis whitespace-nowrap;
  }
  .checkbox-auth {
    @apply h-4 w-4 mr-2;
  }
  .checked {
    @apply line-through decoration-orange-300 text-orange-300;
  }
  .delete-btn {
    @apply inline-flex float-right mt-1;
  }
  .darkMode {
    @apply absolute top-5 right-5;
  }
  .darkModeText {
    @apply text-xl;
  }
  .app-title {
    @apply text-3xl;
  }
  .app-container {
    @apply w-full h-full justify-center items-center flex;
  }
  .app-inner {
    @apply flex mt-5 w-6/12 justify-between;
  }
  .primary-btn {
    @apply py-3 px-12 ml-2 flex text-2xl bg-stone-400 hover:bg-stone-500 text-black dark:bg-orange-600 dark:hover:bg-orange-700 ease-in-out duration-300 dark:text-white rounded-md;
  }
  .input-text {
    @apply py-3 pl-7 text-black border-black dark:text-white text-2xl rounded-md bg-transparent flex-1 dark:border-white border-2;
  }
}

How to move a png or 3D object through the website using GSAP?

I want to design a landing website using HTML and CSS. How do I achieve the scrolling effect when a user scrolling the website and wants to move an animated object through the website? I followed the GSAP and tried to do some scroll trigger animation. This is what I tried:-https://codepen.io/sidath-sansu/pen/jORJ
I wanted to move a PNG image or a 3D animated object from the sketchfab website. I want to design a website like the below image. I found some real websites that used scroll trigger animations to decorate their website. Examples:- bubblidigital, takeboost

enter image description here

I want to move the airplane when scrolling with the dash line path and hide in the last section airplane come and start again at the end of that section. Need to design any kind of cloud movement on the web page while scrolling. Please Help to achieve this design. Please give a source to refer to this kind of design. Please give me the step by step to achieve this with GSAP.

Is there a way to create vertical fixed sections like this in CSS/JS?

I’m trying to create a similar layout where each section shows up with scroll. Is there a way to create this with CSS/JS?

https://www.youtube.com/watch?v=LF7K2zuh-H8

I tried using position fixed and sticky for sections to make this work, but it doesn’t seem to be working.

.scroll_container {
  margin-top: 800px;
  height: 1200px;
  margin-left: 20%;
  position: relative;
  overflow: hidden;
}

.scroll_container div {
  position: sticky;
  position: -webkit-sticky;
  width: 800px;
  height: 400px;
}

.scroll_1 {
  background: orange;
  top: 0px;
}

.scroll_2 {
  top: 400px;
  background: turquoise;
  z-index: 10;
}

.scroll_3 {
  top: 800px;
  background: teal;
  z-index: 20;
}
<div class="scroll_container">
  <div class="scroll_1">
    A wavelike design appears to be flowing across the canvas from left to right. At its heart lies another small cloud, indicating some kind of technological feature or product. -
  </div>

  <div class="scroll_2">
    A wavelike design appears to be flowing across the canvas from left to right. At its heart lies another small cloud, indicating some kind of technological feature or product. -
  </div>

  <div class="scroll_3">
    A wavelike design appears to be flowing across the canvas from left to right. At its heart lies another small cloud, indicating some kind of technological feature or product. -
  </div>
</div>

Increase Request Body Size Limit in NestJS | ERROR [ExceptionsHandler] Request body larger than maxBodyLength limit Error

I’m currently working on a NestJS application where I have a controller responsible for uploading files to BunnyCDN. The function used for the upload accepts a file path and buffer. However, I’m encountering an issue when trying to upload a file with a size of 13MB. The error message I receive is as follows:
ERROR [ExceptionsHandler] Request body larger than maxBodyLength limit
Error [ERR_FR_MAX_BODY_LENGTH_EXCEEDED]: Request body larger than maxBodyLength limit

My controller :

@Post('upload/file')
  @UseInterceptors(
    FileInterceptor('file')
  )
  async upload(@UploadedFile() file): Promise<string> {
    let filePath: string = ''

    const folderPath = 'programme/images'; // upload path in bunny

    if (file) {
      const { buffer } = file;
      const currentDate = new Date().toISOString().replace(/[^a-zA-Z0-9]/g, '_').split('T')[0];
      const currentTime = new Date().toISOString().split('T')[1].replace(/..+/, '').replace(/:/g, '');
      const originalName = file.originalname.replace(/[^a-zA-Z0-9.]/g, '_').replace(/ /g, '_');
      const randomName = `${currentDate}_${currentTime}_${originalName}`;
      filePath = `${folderPath}/${randomName}`;
      await this.bunnyCDNService.uploadFile(filePath, buffer);
    }
    return filePath;
  }

I’ve already attempted to increase the request body size limit using the body-parser middleware in my NestJS application with the following configuration:

app.use(json({ limit: '50mb' }));

Could someone please guide me on how to effectively increase the request body size limit in NestJS for file uploads

Which HTML element or role for a onmouseenter event

I was implementing a feature that display a tooltip by hovering a text. Thinking about accessibility, I am wondering which element or role I should address.
Eg:

<div onMouseEnter={triggerEvent}>This trigger a hover event</div> // Lack of role (button?) 
<button onMouseEnter={triggerEvent}>This trigger a hover event</button> // No onclick event, so is it really the element we need ?

In my opinion, it’s not a button nor a role ‘button’. Any suggestion?

Base is set in vite.config.js but is the wrong value in import.meta.env.BASE_URL

I want to have the ability to set the base URL at build time. This is more for API calls than anything else – I don’t want them going to https://localhost:7251 on production, but I also don’t want to resort to anything convoluted to swap the URLs.

I’ve a vite.config.js file that looks like this:

export default defineConfig (({ command, mode, isSsrBuild, isPreview }) => {
    const commonConfig = {
      build: {
        outDir: '../../wwwroot/dist',
        assetsDir: '',
        emptyOutDir: true,
        manifest: true,
        rollupOptions: {
          input: {
            client: './src/client.js'
          }
        },
      },
      server: {
        port: 5173,
        strictPort: true,
        hmr: {
          clientPort: 5173
        }
      },
      plugins: [
        vue(),
        VueDevTools(),
      ],
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url))
        }
      }
    };

    let envConfig = {};
    if (command === 'serve') { // configure dev, serve is an alias of 'dev'
      envConfig = {
          base: 'https://localhost:7251/'
      };
    } else if (command === 'build') {
      envConfig = {
          // production URL
      };
    }

    return Object.assign(commonConfig, envConfig);
  }
)

According to the Vite docs, if I set the value of ‘base’ in vite.config.js, this will be available as import.meta.env.BASE_URL in the application. Yet everywhere I reference it in the application, the value is / and not https://localhost:7251.

I’m not sure what to try here. I found in the vue docs mention of a define property that supposedly nests env vars, but using it just gave me CORS errors on some new .mjs file.

logic error in my routing function in node js

so I have a pretty common function for routing in my node project. But I’m dealing with a logic error I can’t wrap my head around. As you see I want to render my HTML server side but when I create and serve it to the browser, the image links were broken. so I fix it with this condition and now my images are showing.

else if (parsedURL.pathname.startsWith("/public/")) {
    console.log("image");
    let imagePath = __dirname + parsedURL.pathname;
    fs.readFile(imagePath, (err, content) => {
      if (err) {
        res.writeHead(404);
        res.end("Image not found!");
      } else {
        let mimeType = mimeTypes.lookup(imagePath);
        res.writeHead(200, { "Content-Type": mimeType });
        res.end(content);
      }
    });

but right now It seems like I can’t respond to the queries because whatever I do I can’t get inside the query block.

else if (parsedURL.query.id) {
    console.log("id");

how can I fix this problem and refactor my code?
(excuse me for my bad English)

full code:

// Create A Server That Can send back ststic files
const http = require("http");
const url = require("url");
const fs = require("fs");
const mimeTypes = require("mime-types");
const { lookup } = require("dns");

const database = fs.readFileSync(`${__dirname}/database/movies.json`, "utf-8");
const cardTemplate = fs.readFileSync(
  `${__dirname}/templates/movieCard.html`,
  "utf-8"
);
const mainPageTemp = fs.readFileSync(
  `${__dirname}/templates/mainPage.html`,
  "utf-8"
);

// Creating our server
const server = http.createServer((req, res) => {

  //////////////////////////////////////////////////////
  // THIS IS A SERVER SIDE RENDERING SITE
  //////////////////////////////////////////////////////

  let parsedURL = url.parse(req.url, true);
  //   console.log(parsedURL.query.id);
  if (parsedURL.pathname === "/" || parsedURL.pathname === "/main") {
    console.log("main");
    res.setHeader("X-Content-Type-Options", "nosniff");
    res.writeHead(200, {
      "Content-type": "text/html",
    });

    // 1. GET the 3 most recent posts from the database
    const latestPosts = JSON.parse(database).slice(0, 3);
    // 2. Get the card html template and generate 3 template ane save them inside a variable
    const cardsHtml = latestPosts
      .map((el) => {
        return cardTemplateReplacor(cardTemplate, el, parsedURL);
      })
      .join("n");
    // console.log(cardsHtml);
    // 3. put them inside the mainpage.html template and send it to the enduser
    const output = mainPageTemp.replace(/{%POSTS%}/g, cardsHtml);
    res.end(output);
  } else if (parsedURL.query.id) {
    console.log("id");
  } else if (parsedURL.pathname.startsWith("/public/")) {
    console.log("image");
    let imagePath = __dirname + parsedURL.pathname;
    fs.readFile(imagePath, (err, content) => {
      if (err) {
        res.writeHead(404);
        res.end("Image not found!");
      } else {
        let mimeType = mimeTypes.lookup(imagePath);
        res.writeHead(200, { "Content-Type": mimeType });
        res.end(content);
      }
    });
  }
});

const cardTemplateReplacor = function (template, card, url) {
  let imageLink = `/public/${card.cover}`;
  let moviePageLink = `${url.pathname}?id=${card.id}`;
  let output = template.replace(/{%IMAGELINK%}/g, imageLink);
  output = output.replace(/{%MOVIENAME%}/g, card.title);
  output = output.replace(/{%MOVIELINK%}/g, moviePageLink);
  return output;
};

server.listen(8080, () => {
  console.log("We are listening to request sended to the port 8080");
});

I will have a lot of images on my pages, so I need a way to route my images in all my HTML pages. I tried tweaking my conditions but I haven’t gotten any results so far.

How to prevent auto-scrolling of v-select

I couldn’t find a way to prevent scrolling of v-select in Vuetify 3. It was optional in Vuetify 2 with :menu-props="auto". I have a demo here. Code is like below:

<template>
  <v-app>
    <v-container>
      <v-select v-model="selected" :items="items" />
    </v-container>
  </v-app>
</template>

<script setup>
  import { reactive } from 'vue'
  import { ref } from 'vue'

  const selected = ref('item10')
  const items = reactive([
    'item1',
    'item2',
    'item3',
    'item4',
    'item5',
    'item6',
    'item7',
    'item8',
    'item9',
    'item10',
    'item11',
  ])
</script>

How can I prevent auto-scrolling after I expand component?

I tried programatically prevent scrolling with using ref. ChatGPT suggested using this.$refs.selector.$refs.menu.scrollTop = 0 but selector does not have any $refs.

pug/uikit nav sidebar lost left padding after uikit upgrade

I forked from this https://github.com/chekromul/uikit-ecommerce-template

to build a static github page.

but after I upgrade uikit to latest version, the side navbar lost its left paddings.

before I upgrade uikit

enter image description here

after:

enter image description here

no code changes, only differece is uikit version.

src file path is src/templates/layouts/_informational.pug
and the code is here:

    aside(class="uk-width-1-4 uk-visible@m tm-aside-column")
  section(class="uk-card " +
                "uk-card-default " +
                "uk-card-small"
          uk-sticky="offset: 90; bottom: true;")
    div.uk-container.uk-container-expand
      nav
        ul.uk-nav.uk-nav-default.tm-nav
          each item in informationalNav
            li(class= {"uk-active": item.id == informationalActivePage})
              a(href= item.href)= item.title

i also found this thread,
https://github.com/uikit/uikit/issues/4648
https://github.com/uikit/uikit/issues/4638

as per my understanding, there is a new way to apply the nav horizontal padding, it’s using the nav-container instead, but as I tried a few times, it’s still not working.

one of the codes that i tried:

    aside(class="uk-width-1-4 uk-visible@m tm-aside-column")
  section(class="uk-card " +
                "uk-card-default " +
                "uk-card-small"
          uk-sticky="offset: 90; bottom: true;")
      **div.uk-container.uk-container-expand**
        nav
          ul.uk-nav.uk-nav-default.tm-nav
            each item in informationalNav
              li(class= {"uk-active": item.id == informationalActivePage})
                a(href= item.href)= item.title

thanks in advanced!

What is the Best Practices for React State Management and API Calls

I’m working on a React application where I need to update data in the UI and make corresponding API calls. I’m wondering what the best practice is for handling this scenario to ensure UI consistency and data integrity.

I am following two approaches one of the approach is working another approach is not working.

Approach which is working:

const Approval = () => {
 const [data, setData] = useState([]);

 useEffect(() => {
    fetchApproval();
 },[])

 const fetchApproval = async () => {
    try {
        const res = await ApiService.getApproval(
            API_ENDPOINTS.GET_APPROVAL_LIST,
            tokenId
        );

        if(response?.status === 200){
            const filteredRes = response,approvalList.filter(res=> res.message.includes(Approval_list_key))
            setData(filteredRes)
        }
    }catch (error){
        console.log(error)
    }
 }

 const handleApproval = async (id) => {
    try {
            await ApiService.updateApprovalById(
            API_ENDPOINTS.UPDATE_APPROVALBY_ID,
            tokenId,
            { id, status: "Approved" }
        );
    } catch (error) {
        console.error("Error approving:", error);
    }
};
    

Approach which is not working:

const handleApproval = async (id) => {
    try {
        const updatedData = data.map(item => {
            if (item.id === id) {
                return { ...item, Status: "Approved" };
            }
            return item;
        });
        setData(updatedData);
        // Make PUT request to update the data
        await ApiService.updateApprovalById(
            API_ENDPOINTS.UPDATE_APPROVALBY_ID,
            tokenId,
           updatedData 
        );
    } catch (error) {
        console.error("Error approving:", error);
    }
};

Question:

  1. Why I am not getting anything when I am trying to access State variable data? please let me know what I am missing or what I am doing wrong
  2. In the handleApproval function, I’m updating the component state (data) first and then making the API call to update the approval status. However, I’m wondering if this is the best approach. Should I update the state first and then make the API call, or is it better to directly pass the data to the API call without relying on the component state update?

Additional Context:

  1. What are the advantages and disadvantages of each approach?
  2. How can I determine which approach is best suited for my specific use case?
  3. Are there any potential pitfalls or edge cases to consider with each approach?
  4. Any best practices or recommendations for handling state management and API calls in React applications?

Any insights or guidance on this topic would be greatly appreciated.

how can I run Delta_plugin without getting error=13, Permission denied?

I’m using this bit of code and for now it’s setup as a text input just for testing. Actual command will be hard coded.

I can run commands like “ls” and it will show that the file is there but no matter what I do I can’t run it using “./delta_plugin”

The command would look like this “./delta_plugin /storage/emulated/0/omw/mods/”

private fun shellExec(cmd: String?, workingDir: String? = null): String {
    var output = ""
    try {
        val processBuilder = ProcessBuilder()
        if (workingDir != null) {
            processBuilder.directory(File(workingDir))
        }
        processBuilder.command(cmd)
        val process = processBuilder.start()

        val reader = BufferedReader(InputStreamReader(process.inputStream))
        var line: String?
        while (reader.readLine().also { line = it } != null) {
            output += line + "n" // Add newline for better formatting
        }
        process.waitFor() // Wait for the process to finish
    } catch (e: Exception) {
        Log.e("ShellExec", "Error executing command: ${e.message}")
        output = "Error executing command"
    }
    return output
}

What am I doing wrong? Is this even possible?

  1. Error executing command: Cannot run program “./delta_plugin” (in directory “/storage/emulated/0/omw_nightly/resources”): error=13, Permission denied
  2. Error executing command: Cannot run program “./delta_plugin”: error=2, No such file or directory

Property in MobX is behaving weirdly

I am using Mobx in my react app.

Right now i have this property

    @observable
  messages: IObservableArray<MessageModel> = observable.array();

and then i have a method that uses that property

 @computed
  get AllMessages() {
    console.log('GETTING ALL MESSAGES', this.messages);
    const mostRecentReadMessage = this.getReadMessage();

   return {... some code}
}

The weird thing is, if log the content of this.messages i get the new messages values, but if i try to access it like this.messages[0].chat.text i get the old value.

Any help understanding this will be greatly appreciated.

I am using a React Native Input box and below that a submit button to execute some action.But I am unable to click the submit button in 1st attempt

I am using a React Native Input box and below that a submit button to execute some action.But I am unable to click the submit button in 1st attempt.it takes two attempts to click the submit button.In 1st attemt the keyboard is getting closed and then only I am able to submit.

Here the code.
<TextInput
onlyNumeric = {true}

                    showErrorOnFocus = {false}
                    value={inputValue}
                    isFocus= {true}
                    regex= {RegexConfig.MOBILE}
                    type= {InputTypeToken.MOBILE}
       
                    charLimit= {10}
                    keyboardType= {KeyboardTypeToken.numberPad}
                    placeholder= "Enter mobile number"
                    
                    
                />
            </View>
            <View style={{marginTop:8}}>
                <Button
                    
                    label = {'Continue'}
                    onPress = {() => {}}
                />
            </View>