I’m trying to add an event listener to multiple buttons inside a loop, but it doesn’t seem to work as expected

Clicking a button should log its respective index (e.g., “Button 0 clicked”, “Button 1 clicked”, etc.).

const buttons = document.querySelectorAll(".btn");

for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function() {
        console.log("Button " + i + " clicked");
    });
}
<button type="button" class="btn">Button 1</button>
<button type="button" class="btn">Button 2</button>
<button type="button" class="btn">Button 3</button>
<button type="button" class="btn">Button 4</button>
<button type="button" class="btn">Button 5</button>

The console output doesn’t match the expected button index in some cases.

What am I doing wrong, and how can I fix this?

TypeError: Cannot read properties of undefined in angular JS application

I have created an angular JS app , basically i am trying to upload a file . The page gives an option to select CSV. then there is upload button. Once click it will call java function and upload the file. however, i am getting an error. Mypage.xhtml looks like this where i have added all the code.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CSV Upload</title>
    <!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>-->
   <!-- <script src="app.js"></script>-->
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/jquery.min.js" />
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/angular.min.js"></script>
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/apponboardingModule.js"></script>
    <script src="#{plugins.requestContextPath}/plugin/apponboarding/ui/js/bootstrap.min.js" />
</head>
<body ng-app="csvApp" ng-controller="CsvController">
    <h1>Upload CSV File</h1>
    <input type="file" file-model="myFile"/>
    <button type="button" ng-click="uploadFile()">Upload</button>

<script>
// app.js
var app = angular.module('csvApp', []);

app.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        console.log("inside service");
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
        .then(function(response){
            console.log("File uploaded successfully");
        }, function(error){
            console.log("Error uploading file");
        });
    }
}]);

app.controller('CsvController', ['$scope', 'fileUpload', function($scope,$http, fileUpload){
    $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' );
        console.dir(file);
        var REST_BASE_URL = PluginHelper.getPluginRestUrl("apponboarding");
        console.log('BASE URL is ' );
        console.log(REST_BASE_URL);
        var uploadUrl = REST_BASE_URL+ "/upload";
        console.log('uploadUrl URL is ' );
        console.log(uploadUrl);
        console.log(fileUpload);
        fileUpload.uploadFileToUrl(file, uploadUrl);
        console.log("Controller END");
    };
}]);
</script>
</body>
</html>

But when i click on upload i get an error,

TypeError: Cannot read properties of undefined (reading 'uploadFileToUrl')
    at $scope.uploadFile (pluginPage.jsf?pn=apponboarding:1511:20)
    at fn (eval at compile (angular.min.js:239:266), <anonymous>:4:150)
    at e (angular.min.js:284:187)
    at b.$eval (angular.min.js:148:347)
    at b.$apply (angular.min.js:149:52)
    at HTMLButtonElement.<anonymous> (angular.min.js:284:239)
    at HTMLButtonElement.dispatch (jquery.min.js:3:10316)
    at q.handle (jquery.min.js:3:8343)

The file should be uploaded using the java code below

@PostMapping("/upload")
        public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
            if (file.isEmpty()) {
                log.error("New Function- Empty File Detected-");
                return new ResponseEntity<>("No file uploaded.", HttpStatus.BAD_REQUEST);
            }

            try {
                // Save the file to the server
                log.error("New Function- File Detected-");
                String uploadDir = "uploads/";
                File uploadFile = new File(uploadDir + file.getOriginalFilename());
                file.transferTo(uploadFile);

                return new ResponseEntity<>("File uploaded successfully.", HttpStatus.OK);
            } catch (IOException e) {
                return new ResponseEntity<>("Error uploading file.", HttpStatus.INTERNAL_SERVER_ERROR);
            }

Disable FAB when selecting a different option in WebView

I’m using react-native-webview to load an Amazon product page in my React Native app. The app has a Floating Action Button (FAB) that extracts the product title and price from the page.

However, on product pages like mobile phones, users can select different color or spec options, which triggers a partial page update instead of a full reload. I need to:

Disable the FAB when the user selects a different color/spec option.
Re-enable the FAB once the page has fully rendered again with the updated selection.
How can I detect when a user selects a new option and determine when the page has fully rendered to re-enable the FAB? Any suggestions on handling this efficiently within react-native-webview?

I have tried using onNavigationStateChange and onLoadEnd events.

enter image description here

Thanks

i18next: loading namespace translation for language en failed Error: non of the backend loaded data

right now I try to move from sprockets to jsbundling with esbuild in our rails application.

Therefore I added all of the important dependencies to the package.json and installed everything yarn.

Additionally, the structure is the following:

├── assets
│   ├── javascripts
│       ├── views
│       │   └── js1.js
|       |   └── js2.js
│       └── application.js
        └── globals.js

In the application.js I import most of the libraries and all views related javascripts from the views folder.

All of the view-javascripts are structured like this:

export default (() => {
    //javascript code here
})();

Additionally to those scripts, there is a globals.js which holds jquery deferred objects, on which the view-scripts can listen to.

For our project we want to use i18next, with the current versions.

In the globals.js we initialize the i18next in this way:

import i18next from 'i18next'
import Backend from 'i18next-chained-backend'
import LocalStorageBackend from 'i18next-localstorage-backend/'
import HttpApi from 'i18next-http-backend'

globalVariables.dfd.i18next = $.Deferred();

i18next
    .use(Backend)
    .init({
        backend: {
            backends: [
                LocalStorageBackend,
                HttpApi
            ],
            backendOptions: [{
                enabled: true,
                expirationTime: 10,
                versions: {
                    en: 'v2022-08-03',
                    de: 'v2022-08-03',
                    fr: 'v2022-08-03'
                }
            },
                {
                    loadPath: '/assets/i18next/{{lng}}.json' // {{lng}}-{{ns}}
                }
            ]
        },
        lng: globalVariables.language,
        fallbackLng: {
            'ch': ['de'],
            'default': ['en']
        }
    }).then(() => {
     globalVariables.dfd.i18next.resolve();
     console.log('i18next initialized');
    });

Now, multiple views-javascriptsare listening to this globalVariables.dfd.i18next object and as soon as it is resolved it should execute the code. With this we make sure, that i18next is initialized.:

export default (() => {
  $.when($.ready, order.dfd.i18next).done(() => {
    //do some code
  });
return true;
})();

Somehow it only gets resolved for the first file but not for the second and the following error comes up in the console:

i18next::backendConnector: loading namespace translation for language en failed Error: non of the backend loaded data

As soon as I comment out the HttpApi it seems to work.

My question is, do I have some major issues with the module structure setup and how can I use i18next in this context?

So everything should be initialized correctly also with the deferred objects.

Child component

I have child component (File Uploader) may be render more than one time in the same parent, in my case it rendered 2 time, i tried to upload file into the second rendered component but it upload it into the first (and it take the props for the first component also).

here is my code:

<div class="mt-1 mb-1" v-for="(attach, index) in fileUploaderSettings.fileUploaders" :key="index">
          <FileUploader
            ref="fileUploaderRefs"
            :title="attach.title"
            :allowedExtensions="attach.allowedExtensions"
            :maxSize="attach.maxFileSize * 1024 * 1024"
            :minSize="attach.minFileSize * 1024 * 1024"
            :maxCount="attach.maxFiles"
            :minCount="attach.minFiles"
            :fileUploaderId="attach.id"
            :formId="fileUploaderSettings.id"
            :affectedId="requestId"
            :mode="attach.mode"
            :showCommentsSection="attach.showCommentsSection"
            :commentsSectionMode="attach.commentsSectionMode"
            :formTemplateName="attach.formTemplateName"
            @fileAdded="handleFilesChanged(index, $event)"
          />
        </div>

How to verify if the seller alrealdy has an Appointment in Frappe Framework

I have an Appointment doctype where i need to verify if the Seller already has an appointment when trying to add another one for the same seller, but i have no idea how to do that. I am using a appointment_calendar.js and a appointment.py files.

appointment_calendar.js

frappe.views.calendar["Appointment"] = {
field_map: {
    start: "start_date",
    end: "end_date",
    id: "name",
    allDay: 0,
    title: "client_name",
    status: "status",
},
order_by: "start_date",
get_events_method: "scheduling_system.scheduling_system.doctype.appointment.appointment.get_appointments"};

appointment.py:

   from frappe.model.document import Document
   from datetime import datetime, timedelta
   from frappe.utils import get_datetime

import frappe 

class Appointment(Document):
    pass

@frappe.whitelist()
def get_appointments(start, end):
    appointments = frappe.get_all(
        "Appointment", 
        filters={"start_date": ["between", [start, end]]},
        fields=["name", "start_date", "duration", "client_name", "status"]
    )

    for app in appointments:
        if not app["start_date"]:
            continue  # Pula registros inválidos
        
        if isinstance(app["start_date"], str):
            start_date = datetime.strptime(app["start_date"], "%Y-%m-%d %H:%M:%S")
        else:
            start_date = app["start_date"]

        duration = app.get("duration", "00:00:00")  # Evita erro caso `duration` seja None
        if isinstance(duration, str):
            h, m, s = map(int, duration.split(":"))
            duration = timedelta(hours=h, minutes=m, seconds=s)

        end_date = start_date + duration
        app["start_date"] = start_date.strftime("%Y-%m-%d %H:%M:%S")
        app["end_date"] = end_date.strftime("%Y-%m-%d %H:%M:%S")

    return appointments

Fields in Frappe Frameword

Preserving original global namespace in transpiled JavaScrip

In my web applications, I have many JS files that I include in the HTML body. They define many symbols that I can use directly in <script> elements. Now, I need to use these applications inside a quite old web engine (the traditional MS WebView, which in practice means IE11), but my JS uses a lot of (relatively) new syntax (mainly arrow functions () =>). I managed to configure Webpack and Babel to translate the code, but I lose visibility of symbols unless I explicitly add the export keyword or assign them to corresponding members of the global window object. Although it’s a simple (and, I hope, harmless) code change, I would like to avoid it. Is there a way to instruct Webpack/Babel to preserve symbol visibility as it happens with plain JS scripts in HTML?

Browser not saving a cookie in localhost when authenticating against NodeJS API, even though the cookie is sent

So, I am working on a full stack app, with a backend written in Node with Express. The app is currently on an AWS EC2 instance running using Nginx and pm2, hooked up to the database (also AWS) and seems to work fine when I access it via Postman. I can hit the POST /signin request, give it an email and password and it will return an auth cookie, which Postman then uses for subsequent requests, and I get a 200 OK when I hit GET /subscriptions in Postman.
enter image description here

I am now trying to get the frontend up and running. The FE is a React project using Vite, still on localhost, and I am using React Query and Axios to get and manage my data from the BE.

The problem I cannot solve is that the cookie that the backend sends (and it does send it), does not seem to be saved in the browser no matter what. I’ve tried:

  • Both Firefox and Chrome
  • Using 127.0.0.1 instead of localhost
  • Mapping a custom domain app.something.something to 127.0.0.1 in the hosts file and accessing it that way
  • Connecting to the local version of the app, instad of the AWS one
  • Tweaking Response headers settings in Nginx on the server to no end
  • Adding the cors package to the BE and setting the headers that way (I removed the Nginx config because it resulted in duplicate headers if I had both)
  • Turning off every possible security option for the cookies (Secure, sameSite, httpOnly)

Nothing seems to work, and I’m out of ideas, and can’t seem to find anything else to try on Google or with Copilot. Again, I can authenticate with Postman, so I think the backend is ok, but something is blocking the same thing in the browser, related to being localhost and/or something to do with headers/CORS/something…

This is how the backend server is setup

import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import express from "express";
import morgan from "morgan";
import cors from "cors";
import cookieParser from "cookie-parser";

import router from "./router";
import { createNewUser, signIn } from "./handlers/users";
import { protect } from "./modules/auth";

const app = express();

const corsOptions = {
  origin: "http://localhost:5173", // I've changed this to match whatever way I'm accessing localhost 
  credentials: true,
};

app.use(cookieParser());
app.use(cors(corsOptions));

This is how I set the cookie on successfull login:

  const token = createJWT(user);

  res.cookie("token", token, {
    httpOnly: true,
    secure: false,
    sameSite: "None",
  });

  res.json("Authentication success");

And this is how I fetch it with Axios on the FE

export const authApi = axios.create({
  baseURL: API_URL,
  withCredentials: true,
});

authApi.defaults.headers.common["Content-Type"] = "application/json";

export const loginUser = async (user: LoginInput) => {
  const response = await authApi.post<ILoginResponse>("/signin", user);
  return response.data;
};

And no matter what I can see the cookie on the response in Firefox
enter image description here

But it seems to not get saved (when I go to Storage > Cookies it’s empty), and not get sent back on the subsequent requests, resulting in the 401s that you see.

Here are the headers for POST /signin

enter image description here

Any help is much appreciated, I’ve wasted two days on this and have no idea what else to try.

How to Set Initial State in Redux Based on Window Size in React/Next.js (TypeScript)?

I’m working on a React + Next.js (TypeScript) project using the Redux Toolkit. I want to set the initial state according to the window size.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface SidebarState {
  collapsed: boolean;
  active: string;
  
}

const initialState: SidebarState = {
  collapsed: false,
  active: "dashboards"
};

here i want collapsed false if window size is less then 1024px if greater make here true.

if we use here

const initialState: SidebarState = {
  collapsed: typeof window !== undefined ? window.innerWidth < 1024 : false,
  active: "dashboards"
};

showing error

ReferenceError: window is not defined

When dragging and dropping a large number of files, event.dataTransfer.items contains only 100

When dragging and dropping a large number of files, event.dataTransfer.items contains only 100.

If I download >100 files, items = 100.
How can I fix it? Need all files and is not directory.
enter image description here

const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('drop', async (event) => {
  event.preventDefault();
  dropZone.classList.remove('dragover');

  const items = event.dataTransfer.items;
  console.log(items)
})
.drop-zone {
  border: 1px solid black;
}
<div id="dropZone" class="drop-zone">
  <p>Drag your image directory here</p>
</div>

Creating extension for Firefox ( add-on ) for search

enter image description hereI am trying to create an extension ( add-on ) for Firefox.

The problem is it does not show icon. It works fine does what i want it to do but i can’t seem to make icon appear.

{
    "manifest_version": 2,
    "name": "MyDramaList Search",
    "version": "1.0",
    "description": "Adds MyDramaList as a search engine option",
    "chrome_settings_overrides": {
        "search_provider": {
            "name": "MyDramaList",
            "search_url": "https://mydramalist.com/search?q={searchTerms}",
            "keyword": "mdl",
            "favicon_url": "favicon.ico",
            "is_default": false,
            "encoding": "UTF-8"
        }
    },
    "icons": {
        "48": "icon.png"
    }
}

given code is saved as manifest.json and it works fine but instead of icon it shows black box like in the image given.

Given code is saved as manifest.json and it works fine but instead of icon it shows black box like in the image given.

Can someone help me with the icon.

Why does the coercion fail for ++ in this example?

class Variable {
  #value;
  #dependents = new Set();
  constructor(value) {
    this.value = value;
  }
  get value() { return this.#value; }
  valueOf() { return this.value; }
  toString() { return String(this.value); }
  toNumber() { return Number(this.value); }
  set value(value) {
    if (this.#value === value)
      return;
    this.#value = value;
    var change = new WeakSet();
    for (const dep of this.#dependents)
      dep.update(change);
  }
  register(dependent) {
    if (!(dependent instanceof Dependent))
      throw new TypeError("Not a Dependent");
    this.#dependents.add(dependent);
  }
}

class Dependent extends Variable {
  constructor(variables, calculation) {
    super();
    this.variables = variables;
    this.calculation = calculation;
    for (const variable of variables) {
      if (!(variable instanceof Variable))
        throw new TypeError("Not a Variable");
      variable.register(this);
    }
    this.calculate();
  }
  update(change) {
    if (change.has(this))
      throw new Error("Cyclic dependency");
    change.add(this);
    this.calculate();
  }
  calculate() {
    this.value = this.calculation(...this.variables);
  }
}

var a = new Variable(1);
var b = new Variable(1);
var c = new Dependent([a, b], (a, b) => a + b);
console.log(`${a} + ${b} = ${c}`);
a.value++;
console.log(`${a} + ${b} = ${c}`);
a++;
console.log(`${a} + ${b} = ${c}`);

Coercion works for a + b but fails for a++. Why?

Collage getting cut when printed

I have the following code where i create a collage and then save it as JPEG or print it. But it is not getting printed or saved properly.

When printed or saved the bottom of the collage gets removed around the text boxes. I’m not sure whats causing the problem.

I’ve tried to use a fixed A4 size for the print and saving. but it still gets cut off, before I add images to the collage, I can print it on A4 size. but when the images are added the collage stretches and it gets out of size.

let nextIndex = 0;

function uploadImages(event) {
  const files = event.target.files;
  const collageItems = document.querySelectorAll('.collage-item');

  for (let i = 0; i < files.length && nextIndex < collageItems.length; i++) {
    const reader = new FileReader();
    reader.onload = function(e) {
      collageItems[nextIndex].src = e.target.result;
      nextIndex++;
    }
    reader.readAsDataURL(files[i]);
  }
}


function saveAsJPEG() {
  const collage = document.getElementById('collage');
  html2canvas(collage).then(canvas => {
    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/jpeg', 1.0);
    link.download = 'collage.jpeg';
    link.click();
  }).catch(error => {
    console.error('Error saving collage as JPEG:', error);
  });
}

function printCollage() {
  const collage = document.getElementById('collage');
  html2canvas(collage).then(canvas => {
    const imgData = canvas.toDataURL('image/jpeg', 1.0);
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
                    <html>
                    <head>
                        <title>Print Collage</title>
                        <style>
                            @page { size: A4; margin: 0; }
                            body { margin: 0; }
                            img { width: 210mm; height: 297mm; }
                        </style>
                    </head>
                    <body>
                        <img src="${imgData}" />
                    </body>
                    </html>
                `);
    printWindow.document.close();
    printWindow.onload = function() {
      printWindow.print();
    }
  }).catch(error => {
    console.error('Error printing collage:', error);
  });
}

function addTextBox() {
  const collage = document.getElementById('collage');
  const textBox = document.createElement('div');
  textBox.className = 'text-box';
  textBox.contentEditable = true;
  textBox.innerText = ''; // Remove default text
  collage.appendChild(textBox);

  makeElementDraggable(textBox);
}

function makeElementDraggable(element) {
  let offsetX, offsetY;
  element.onmousedown = function(event) {
    offsetX = event.clientX - parseInt(window.getComputedStyle(element).left);
    offsetY = event.clientY - parseInt(window.getComputedStyle(element).top);
    document.onmousemove = function(event) {
      element.style.left = (event.clientX - offsetX) + 'px';
      element.style.top = (event.clientY - offsetY) + 'px';
    }
    document.onmouseup = function() {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }
}
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0;
  padding: 0;
  background-color: #f0f0f0;
}

#collage-container {
  display: flex;
  align-items: flex-start;
  margin-top: 20px;
}

#collage {
  display: grid;
  grid-template-columns: repeat(3, 70mm);
  grid-template-rows: repeat(3, 99mm);
  width: 210mm;
  height: 297mm;
  gap: 0;
  border: 1px solid black;
  background: white;
  position: relative;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.collage-item {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

@media print {
  @page {
    size: A4;
    margin: 0;
  }

  body {
    margin: 0;
    padding: 0;
  }

  #collage {
    width: 210mm;
    height: 297mm;
    overflow: hidden;
  }

  .card,
  .btn-container,
  .link {
    display: none;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Collage</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>

<body>
  <div id="collage-container">
    <div id="collage">
      <img src="https://picsum.photos/300/200" alt="Item 1" class="collage-item" id="item1">
      <img src="https://picsum.photos/300/200" alt="Item 2" class="collage-item" id="item2">
      <img src="https://picsum.photos/300/200" alt="Item 3" class="collage-item" id="item3">
      <img src="https://picsum.photos/300/200" alt="Item 4" class="collage-item" id="item4">
      <img src="https://picsum.photos/300/200" alt="Item 5" class="collage-item" id="item5">
      <img src="https://picsum.photos/300/200" alt="Item 6" class="collage-item" id="item6">
      <img src="https://picsum.photos/300/200" alt="Item 7" class="collage-item" id="item7">
      <img src="https://picsum.photos/300/200" alt="Item 8" class="collage-item" id="item8">
      <img src="https://picsum.photos/300/200" alt="Item 9" class="collage-item" id="item9">
    </div>
    <div class="card">
      <div class="btn-container">
        <label class="btn-upload" for="file-upload" title="ዘጠኝ ፖስተሮችን በአንዴ መምረጥ ወይም አንድ በአንድ መምረጥ ይችላሉ"><i class="fas fa-upload"></i>Choose Images | ፖስተር አስገባ</label>
        <input type="file" id="file-upload" accept="image/*" multiple onchange="uploadImages(event)">
        <button class="btn-add-text" onclick="addTextBox()"><i class="fas fa-font"></i>Add Text | ጽሁፍ አስገባ</button>
        <button class="btn-save" onclick="saveAsJPEG()"><i class="fas fa-save"></i>Save as JPEG | ሴቭ አርግ</button>
        <button class="btn-print" onclick="printCollage()"><i class="fas fa-print"></i>Print Collage | ፕሪንት አርግ</button>
      </div>

    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</body>

</html>

React – cannot replace values inside dangerouslySetInnerHTML with DOMPurify

I have the following piece of ReactJS code that displays the value of the variable bodyHtml that contains html as a string.

I would like all links, inside the html string contained in the variable, to open in a new tab.

I am using the DOMPurify library and the following code works only if I remove purify.sanitize.

If I use purify.sanitize instead the replaceAll has no effect.

How can I get around this problem?

This doesn’t work:

dangerouslySetInnerHTML={{
    __html: purify.sanitize(
        bodyHtml.replaceAll('href', 'target="_blank" href')
    )
}}

While this works:

dangerouslySetInnerHTML={{
    __html: bodyHtml.replaceAll('href', 'target="_blank" href')
}}

Google Maps InfoWindow: How to Move the Close Button to the Right of the Content and remove the empty space which is on top of the Content?

I noticed that in the last few months google maps has changed its API and the info window that shows up when one clicks on a marker is rendered differently now.

https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

There is a weird div that appears during inspection:
enter image description here

Would like the info window the margin on top of the text to be removed and to like this (as it was before the recent changes in google maps):
enter image description here