How to force event handler to take precedence?

I have JavaScript code, in which I change the input field css class on invalid event to add an error class to a parent div having the class form-row.

I furthermore attach then an event listener on the form fields fields on input and click to remove the error class once the user interacts with the form fields (text, textarea, dropdown select boxes, …)

Now, those form fields already have event handlers attached, and some stop event propagation.

Certain elements won’t call formElementRow.classList.remove('error'); as some other event handler acts first.

Is there a quick way to force my event handler that I define here to take precdence while still allowing the other event handlers to act on the page?

I control the html of the form, I do not want to change anything with the code that registers the other event handlers.

This is my code that works for all my form elements except those who stop the event propagation:

const formErrorStatesOnBrowserSideValidation = () => {
    const targetClass = '.form-row';
    document.addEventListener('invalid', (invalidEvent) => {
        const {target} = invalidEvent;
        const formElementRow = target.closest(targetClass);

        if (formElementRow) {
            formElementRow.classList.add('error');
        }

        ['input', 'click'].forEach(event => {
            // some elements have other js / jQuery applied to them that stops event propagation hence the class removal is never called to those
            target.addEventListener(event, () => {
                formElementRow.classList.remove('error');
            });
        });
    }, true);
};
formErrorStatesOnBrowserSideValidation();

This is a follow-up question from: What event to listen for when a user clicks submit button in html5 invalid form?

What is the Polarion Velocity starting point event for JavaScript code?

We want to render an external app that needs the encoded project id as a query parameter and tried the following

#set( $projectId = $page.fields.project.projectId() )
 
<iframe 
 id="app-container"
    frameborder="0" 
    style="height:100vh; 
    width: 100vw;">
</iframe>
 
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const encodedProjectId = encodeURIComponent($projectId);
        const iframe = document.getElementById("app-container");
        iframe.src = `/external-app?project-id=${encodedProjectId}`;
    });
</script>

Unfortunately this doesn’t work because the “DOMContentLoaded” event never triggers. What is the mount-hook for JavaScript code inside Velocity code?

Web OTP API in Angular Not Triggering After User Clicks Allow

I’m working on implementing an Angular directive using the Web OTP API to auto-populate OTP inputs from an SMS message. Despite the user clicking “Allow” to grant permission, the navigator.credentials.get part doesn’t trigger the expected .then() code to populate the inputs.

Here’s a summary of my directive and HTML setup:

Directive Code:

import { Directive, ElementRef, Input, OnDestroy, OnInit } from '@angular/core';
import { ControlContainer, FormGroupDirective } from '@angular/forms';
import { ChangeDetectorRef } from '@angular/core';

interface CredentialRequestOptions {
  otp: any;
  signal: any;
}

@Directive({
  selector: '[appWebOtp]',
  standalone: true
})
export class WebOtpDirective implements OnInit, OnDestroy {
  private ac = new AbortController();
  private timer: any;

  @Input('timeout') timeout?: number;

  constructor(
    private el: ElementRef,
    private controlContainer: ControlContainer,
    private cdRef: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    const options: CredentialRequestOptions = {
      otp: { transport: ['sms'] },
      signal: this.ac.signal
    };

    navigator.credentials.get(options).then((otp: any) => {
      if (otp && otp.code) {
        this.populateOtpInputs(otp.code);
      }
    }).catch(err => {
      console.log(err);
    });

    if (this.timeout) {
      this.timer = setTimeout(() => {
        this.ac.abort();
      }, this.timeout);
    }
  }

  ngOnDestroy(): void {
    this.ac.abort();
    if (this.timer) {
      clearTimeout(this.timer);
    }
  }

  private populateOtpInputs(code: string): void {
    const formGroup = (this.controlContainer as FormGroupDirective).form;
    const inputs = this.el.nativeElement.querySelectorAll('input[autocomplete="one-time-code"]');

    code.split('').forEach((char, index) => {
      const input = inputs[index];
      const controlName = input.getAttribute('formControlName');
      if (controlName && formGroup.get(controlName)) {
        formGroup.get(controlName)?.setValue(char);
        input.value = char;
      }
    });

    this.cdRef.detectChanges();
  }
}

HTML Template:

<form id="otp-form" appWebOtp [formGroup]="form" class="flex flex-wrap justify-center basis-full" dir="ltr">
  <input autocomplete="one-time-code" required type="text" id="digit1" formControlName="digit1" maxlength="1" autofocus>
  <input autocomplete="one-time-code" required type="text" id="digit2" formControlName="digit2" maxlength="1">
  <input autocomplete="one-time-code" required type="text" id="digit3" formControlName="digit3" maxlength="1">
  <input autocomplete="one-time-code" required type="text" id="digit4" formControlName="digit4" maxlength="1">
</form>

Problem: When using this directive, even if the user clicks “Allow” to permit access, navigator.credentials.get(options).then(…) doesn’t trigger. I expect it to call this.populateOtpInputs(otp.code) and populate the input fields with the OTP, but nothing happens after the user approval.

What I Tried:

Adding this.cdRef.detectChanges() after populating inputs to trigger Angular’s change detection.

Setting a timeout with AbortController to limit the waiting period.

Verifying permissions and compatibility with the Web OTP API.

Question:

Why does navigator.credentials.get(options).then(…) not execute after user permission, and what additional steps or changes are needed to make it work?

Any insights into why navigator.credentials.get may not be triggering after the user clicks allow, or potential solutions, would be highly appreciated!

JavaScript for preloading images in the background/cache with progress bar

I am trying to get the data-value of the .ldBar.label-center div to update along with the loading progress of the images loaded in the background, within preloadImages.

I guess my goal would be to get the eventListener to update the data-value object live, so that people waiting can follow the progress of the huge pile of images they have to download into cache before entering the content of the page.

this.addEventListener("DOMContentLoaded", preloadImages, true);

var imageArray = new Array("bigImage.jpg");

function preloadImages(e) {
  for (var i = 0; i < imageArray.length; i++) {
    var tempImage = new Image();

    tempImage.addEventListener("load", trackProgress, true);
    tempImage.src = imageArray[i];
  }
}

function trackProgress() {
  loadedImages++;
  if (loadedImages == imageArray.length) {
    imagesLoaded();
  }
}

function imagesLoaded() {
  // do something
}
.ldBar-label {
  color: #ffffff;
  font-family: 'Lato', sans-serif;
  font-size: 5em;
  font-weight: 900;
  -webkit-text-stroke: 3px black;
}

.ldBar path.mainline {
  /* styling of bar omitted */
}
<div class="ldBar label-center" data-value="60" data-type="fill" data-img="media/886679_9d816.gif" data-img-size="400,400" data-fill-background="#9df"></div>

Fully responsive collapsible images not functioning correctly

I have a wall of images and when an image is clicked a separate div rolls down underneath the row in which the image was clicked. At the moment it is fully responsive, meaning when the screen size is reduced it creates more rows and the collapsible always drops down underneath the image row. I need the collapsible div to span across the full container.

However, in my code now, the collapsible div, with class .info, keeps shifting left and right depending which image is being clicked. I just want the .info div to stay within the container and stay in the same place for each row.

For example, when an image is clicked on in the first row the .info div rolls down and shows the information. Then, when the third image on the same row is clicked the .info div is in the same place, but just the text changes. Then, when an image on the second row is clicked the .info on the first row is closed then the .info div opens up underneath the second row spanning the full container width.

function toggleInfo(element) {
  const allPartners = document.querySelectorAll('.partner');
  allPartners.forEach(partner => {
    if (partner !== element) {
      partner.classList.remove('active');
    }
  });

  element.classList.toggle('active');
}
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 20px;
  overflow-x: hidden;
  /* Prevent horizontal scrolling */
}

.container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.partner {
  position: relative;
  width: calc(25% - 5px);
  /* 4 images per row with 5px gap */
  cursor: pointer;
  margin-bottom: 20px;
  /* Space for the info box */
}

.image-wrapper {
  position: relative;
  overflow: hidden;
}

.image-wrapper img {
  width: 100%;
  height: auto;
  display: block;
  transition: opacity 0.3s;
}

.gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  display: flex;
  justify-content: center;
  align-items: center;
}

.name {
  color: white;
  font-size: 1.5rem;
  z-index: 1;
}

.info {
  display: none;
  background-color: white;
  padding: 10px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  position: relative;
  width: 100vw;
  left: 10px;
  /* Adjust for body padding */
  transform: translateX(-50%);
  margin-top: 10px;
  margin-left: 0;
  margin-right: 0;
  box-sizing: border-box;
}

.partner.active .info {
  display: block;
  animation: slideDown 0.3s ease;
}

.partner.active .image-wrapper img {
  opacity: 1;
}

.partner:not(.active) .image-wrapper img {
  opacity: 0.5;
}

@keyframes slideDown {
  from {
    max-height: 0;
    opacity: 0;
  }
  to {
    max-height: 500px;
    /* Adjust as needed */
    opacity: 1;
  }
}


/* Responsive Design */

@media (max-width: 800px) {
  .partner {
    width: calc(50% - 5px);
    /* 2 images per row on smaller screens */
  }
}

@media (max-width: 500px) {
  .partner {
    width: 100%;
    /* 1 image per row on very small screens */
  }
}
<div class="container">
  <!-- Generate 8 partner entries with placeholder images -->
  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 1">
      <div class="gradient">
        <span class="name">Partner 1</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 1...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 2">
      <div class="gradient">
        <span class="name">Partner 2</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 2...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 3">
      <div class="gradient">
        <span class="name">Partner 3</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 3...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 4">
      <div class="gradient">
        <span class="name">Partner 4</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 4...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 5">
      <div class="gradient">
        <span class="name">Partner 5</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 5...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 6">
      <div class="gradient">
        <span class="name">Partner 6</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 6...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 7">
      <div class="gradient">
        <span class="name">Partner 7</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 7...</p>
    </div>
  </div>

  <div class="partner" onclick="toggleInfo(this)">
    <div class="image-wrapper">
      <img src="https://via.placeholder.com/200x300" alt="Partner 8">
      <div class="gradient">
        <span class="name">Partner 8</span>
      </div>
    </div>
    <div class="info">
      <p>More information about Partner 8...</p>
    </div>
  </div>
</div>

How to remove escape characters in K6 js

I’m trying make a POST request using K6. I’m fetching the request body from a APIs.json file in my script.js. When I try to use the request body in script.js file it now consists of escape characters. How do I get rid of them? I tried JSON.parse and JSON.stringify, but did not work.

APIS.json:

{
    "apiRequests":
    [
        {
            "requestVerb" : "POST",
            "requestHeaders" : [{"Content-Type":"application/json","Authorization":"Bearer $ACCESS_TOKEN"}],
            "requestEndpoint" : "/individual",
            "apiName": "management-4",
            "target": "target1",
            "responseVariables": ["id","name"],
            "responseHeaders": [""],
            "requestBody": {"title":"Mr","givenName":"Rohit","familyName":"Reddy"}
        }
    ]
}

script.js

// To perform testing
import http from 'k6/http'
// To import API requests file
// import { open } from 'k6/fs';

const host = __ENV.HOST;
console.log(`Testing host = ${host}`);

// Ignore certificates
export const options = {
    insecureSkipTLSVerify: true
};

// GET API Requests
let apiRequests = JSON.parse(open('./APIs.json'));
console.log(`log = ${apiRequests}`);

apiRequests = JSON.stringify(apiRequests);
console.log(`Stringify = ${apiRequests}`);


// K6 Main function
export default function() {
    let httpVerb = "get";
    http[httpVerb](`https://${host}/health/v1/health`);
}

Output:

time="2024-11-11T08:09:31Z" level=info msg="log = [object Object]" source=console
time="2024-11-11T08:09:31Z" level=info msg="Stringify = {"apiRequests":[{"requestVerb":"POST","requestHeaders":[{"Content-Type":"application/json","Authorization":"***"}],"requestEndpoint":"/individual","apiName":"management-4","target":"target1","responseVariables":["id","name"],"responseHeaders":[""],"requestBody":{"title":"Mr","givenName":"Rohit","familyName":"Reddy"}}]}" source=console

Expected output:

time="2024-11-11T08:09:31Z" level=info msg="log = [object Object]" source=console
time="2024-11-11T08:09:31Z" level=info msg="Stringify = {"apiRequests":[{"requestVerb":"POST","requestHeaders":[{"Content-Type":"application/json","Authorization":"***"}],"requestEndpoint":"/individual","apiName":"management-4","target":"target1","responseVariables":["id","name"],"responseHeaders":[""],"requestBody":{"title":"Mr","givenName":"Rohit","familyName":"Reddy"}}]}" source=console

why blob not working while in new Image src

 <input type="file" @change="handleUpdateFIle">

I’m having trouble running the following code snippet in my application. When I try to set the src of an img element using the result of a FileReader object, I get an error saying “img src is not valid”. Can you help me fix this issue?

const handleUpdateFIle = (e: file) => {
  const file= e.target.files[0]
  const reader = new FileReader()
  const img = new Image()
  reader.onload = () => {
      const arrayBuffer = reader.result
      const blob = new Blob([arrayBuffer],{type: file.type || 'image/png'})
      console.log('blob',blob)
      const URL = window.URL || window.webkitURL
      const url = URL.createObjectURL(blob)
      img.src = url
   //img.src blob:http:xxx
  }
  reader.readAsArrayBuffer(file)
}

console tip

Uncaught (in promise) img src is not valid

I’ve tried using readAsDataURL instead of readAsArrayBuffer, but I still get the same error. Can you please provide a solution?

img.src = URL.createObjectURL(file)

3d object should always “fit” inside the window with Orthographic Camera

I want my 3d objects to always “fit” inside the window
This is how my code currently looks like

export function onWindowResize(camera, renderer) {
  const canvas = renderer.domElement;
  const width = window.innerWidth;
  const height = window.innerHeight;
  const connection = getBoundingBox(connectionGroup);
  const needResize = canvas.width !== width || canvas.height !== height;
  const isPortrait = connection.width < connection.height;

  if (needResize) renderer.setSize(width, height);

  const aspect = isPortrait ? width / height : height / width;
  const frustumSize = Math.max(connection.width, connection.height);

  //Front View
  if (isPortrait) {
    camera.left = (-frustumSize * aspect) / 2;
    camera.right = (frustumSize * aspect) / 2;
    camera.top = frustumSize / 2;
    camera.bottom = -frustumSize / 2;
  } else {
    camera.left = -frustumSize / 2;
    camera.right = frustumSize / 2;
    camera.top = (frustumSize * aspect) / 2;
    camera.bottom = (-frustumSize * aspect) / 2;
  }

  camera.updateProjectionMatrix();
}

Currently, everything works as expected: the object fits in the window based on its height or width. A problem occurs if the object’s height exceeds the window height but still fits within the maximum width (vice-versa), causing the model to be cropped.

I only need to fit the object on the initial display, user can perform orbit controls freely after that

MAX WIDTH

MAX HEIGHT

MAX WIDTH but models height exceed window/camera height

I tried manually setting camera.zoom, but even then, I couldn’t figure out the right value for it. After that, my orbit controls stopped functioning.

Real life usage of generators functions in js

const foo = function* () {
  yield 'a';
  yield 'b';
  yield 'c';
};

let str = '';
for (const val of foo()) {
  str = str + val;
}

console.log(str);
// Expected output: "abc"

This is a example of js generators function. But where are we going to use this function in daily software development.

Like Closure applications are private variables implementation, counter, rate limitter.

How to keep the logo in the center of the video component in any resolution of the screen

I have a React component that has a video with a company logo in the center, but when I switch to a responsive screen like a cellphone the logo keep getting out of the video, how do I fix this?

PC Version

Iphone Version

import videoJacare from '../imgs/ny4k.mp4';
import imgTest from '../imgs/LogoFecapFinanceOriginal2.png';
import styled from "styled-components";

function video(){
  return(
    <Intro>
      <Logo src={imgTest} alt="" />
      <Jacare
        src={videoJacare}
        poster={imgTest}
        loop
        autoplay="true"
        muted
        playsInline
        preload
        disablePictureInPicture
      >
        Seu navegador não suporta o elemento de vídeo.
      </Jacare>
    </Intro>
  );
}

const Jacare = styled.video`
width: 100%;         
  height: auto;        
  max-height: 80vh;    
  object-fit: cover;   
  align-items: center;
`

const Texto = styled.h1`
  position: absolute;
  top: 60%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #fff;
`

const Intro = styled.div`
  text-align: center;
  align-items: center;
  position: relative;
`

const Logo = styled.img`
  position: absolute; 
  top: 50%; 
  left: 50%;
  transform: translate(-50%, -50%); 
  text-align: center;
  color: #fff;
  max-width: 25%;
  max-height: 25%;
  transition: all 0.3s ease-in-out;
`

export default video;

I’ve tried using position functionalities, the z-index that is used to the logo never get out of the video, but it did, but nothing seems to work.

ARGON dashboard router / problems adjusting the routes

I’m having problems customizing the routes.js. I would like to go directly to the login (Login.vue) when I initially call it with / or /login. How can I customize the default routes.js correctly? The app always goes to the dashboard first.

const routes = [
  {
    path: '/',
    redirect: 'dashboard',
    component: DashboardLayout,
    children: [
      {
        path: '/dashboard',
        name: 'dashboard',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "demo" */ '../views/Dashboard.vue')
      },
      {
        path: '/icons',
        name: 'icons',
        component: () => import(/* webpackChunkName: "demo" */ '../views/Icons.vue')
      },
      {
        path: '/profile',
        name: 'profile',
        component: () => import(/* webpackChunkName: "demo" */ '../views/Pages/UserProfile.vue')
      },
      {
        path: '/maps',
        name: 'maps',
        component: () => import(/* webpackChunkName: "demo" */ '../views/GoogleMaps.vue')
      },
      {
        path: '/tables',
        name: 'tables',
        component: () => import(/* webpackChunkName: "demo" */ '../views/RegularTables.vue')
      }
    ]
  },
  {
    path: '/',
    redirect: 'login',
    component: AuthLayout,
    children: [
      {
        path: '/login',
        name: 'login',
        component: () => import(/* webpackChunkName: "demo" */ '../views/Pages/Login.vue')
      },
      {
        path: '/register',
        name: 'register',
        component: () => import(/* webpackChunkName: "demo" */ '../views/Pages/Register.vue')
      },
      { path: '*', component: NotFound }
    ]
  }
];

Making JS calls offline [closed]

I have a minified JS file which is available at https://cdn.jsdelivr.net/npm/@lottiefiles/[email protected]/dist/lottie-player.min.js (known vulnerable) I would like to make all API calls made by the file offline so it should run even if it is offline. What is the most easiest way of doing that? I will be running it on a system with no internet access. I know I have to make changes to domain name to host everything on local. But is there a quick solution?

Javascript encryption and decryption

I am trying to create a encryption/decryption functionality similar to a java code given below.

private static byte[] encryptPKCS7(byte[] plainData, PublicKey pubKey) throws
            Exception {
        CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
        JcaAlgorithmParametersConverter paramsConverter = new
                JcaAlgorithmParametersConverter();
        OAEPParameterSpec oaepParamSpec = new OAEPParameterSpec("SHA-256",
                "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
        AlgorithmIdentifier algoId =
                paramsConverter.getAlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP,
                        oaepParamSpec);
        JceKeyTransRecipientInfoGenerator recipInfo = new
                JceKeyTransRecipientInfoGenerator(KEY_IDENTIFIER.getBytes(), algoId, pubKey)
                .setProvider(bcProvider);
        gen.addRecipientInfoGenerator(recipInfo);
        CMSProcessableByteArray data = new CMSProcessableByteArray(plainData);
        BcCMSContentEncryptorBuilder builder = new
                BcCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC);
        CMSEnvelopedData enveloped = gen.generate(data, builder.build());
        return enveloped.getEncoded();
    } 

The javascript code I came up with is,

function decryptText(encryptedText) {
    const privateKey = fs.readFileSync('PrivateKey.pem', 'utf8');
    const encryptedBuffer = Buffer.from(encryptedText, 'base64');
    const decryptedBuffer = crypto.privateDecrypt({
        key: privateKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
        oaepHash: 'sha256'
    }, encryptedBuffer);
    return decryptedBuffer.toString('utf8');
}

using forge

function encryptPKCS7(plainData, pubKey) {
    const p7 = forge.pkcs7.createEnvelopedData();
    p7.addRecipient(pubKey);
    p7.content = forge.util.createBuffer(plainData, 'utf8');
    p7.encrypt();
    return forge.util.encode64(p7.toAsn1().getBytes());
}

The java and javascript encryption is not matching.

vs code macro for wrapping code in if statement

i want to create a macro for wrapping a selected line of code in if statement in vs code. i stumbled upon this youtube video about macros in vs code so i tried imitating the ‘ifWrap’ in the video but for some reason it just doesn’t seem to work. first download the macro-commander extension. then paste the this code in settings.json file and create the snippet need for it. and that’s it, everything should have worked but it didn’t so here is the code,

"editor.action.clipboardCutAction",
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "name": "iff"
        }
      },
      {
        "command": "type",
        "args": {
          "text": "true"
        }
      },
      "cursorLineEnd",
      "cursorDown",
      "editor.action.clipboardPasteAction"

this is the snippet that it uses(it doesn’t have scope i don’t know why but it is not allowed for some reason),

"iff":{
    "prefix": "iff",
    "body": [
        "if ($1) {",
        "t$0",
        "}"
    ],
    "description": "iff",
}

please help me and thank you.

i tried finding article related to it, tried asking questions to chatgpt, notebooklm, gemini but it didn’t worked.