JS remove class Name dynamically

I have a requirement to remove a class name dynamically via js.

The reason to do so is that I’m trying to remove the icon of sorting a specific column from a table.

When I inspect the element – I see I have ng-class with the same class name as the class attribute.

I don’t have any access to the angular file – since it’s a third-party app, but I can write some JS in it.

<th title="" ng-repeat="$column in $columns" ng-class="{
   'sortable': $column.sortable(this),
   'sort-asc': params.sorting()[$column.sortable(this)]=='asc',
   'sort-desc': params.sorting()[$column.sortable(this)]=='desc'
   }" class="col_poi_Id_356 sortable">
</th>

When I’m removing the “sortable” from the class manually from the developer console – It works great.

But when I’m trying to do: element.remove("sortable"); it removes the “sortable” both from the class and from the ng-class and its causes unwanted behavior.

I want to remove a class name only from the class attribute without touching the ng-class.

is that possible?

I don’t have much knowledge in JS, but I tried to find a solution on the google but didn’t find one.

any help, including links, will be much appreciated.

Thanks!

JS/React: Replace ids by values from constant

I’ll be glad for any hint!
I have an array:

"languages": [
    {
        "languageId": 1,
        "languageLevelId": 2
    },
    {
        "languageId": 9,
        "languageLevelId": 3
    },
    {
        "languageId": 0,
        "languageLevelId": 3
    }
]

And constants:

export const LANGUAGE = {
    UKRAINIAN: 0,
    ENGLISH: 1,
    CHINESE: 2,
    SPANISH: 3,
    ARABIC: 4,
    JAPANESE: 5,
    HINDUSTANI: 6,
    FRENCH: 7,
    GERMAN: 8,
    RUSSIAN: 9,
    PORTUGUESE: 10,
    ITALIAN: 11
};

export const LANGUAGE_LEVEL = {
    BEGINNER: 0,
    INTERMEDIATE: 1,
    ADVANCED: 2,
    NATIVE: 3
};

How can I get something, like:

"languages": [
    {
        "languageId": ENGLISH,
        "languageLevelId": ADVANCED
    },
    ...
]

And then map languages, or what should I do in order to get such a result and get:
And then map languages, or what should I do in order to get such a result and get:

<div>English</div>
<div>Advanced</div>

Get original implementation during jest mock

I’m trying to temporarily mock node-fetch in an ESM module while still retraining the original implementation so I can access a real endpoint’s value. However, this errors with “Must use import to load ES Module.” I recognize jest support for ESM is still pending – is there any way to have this behavior in a combination of current Node, ES6, and Jest?

worker.ts (dependency):

export default async () => {
    const response = await fetch("http://example2.org");
    return await response.json()
  }

main.test.ts:

import { jest } from "@jest/globals";


jest.mock("node-fetch", () => {
    return Promise.resolve({
        json: () => Promise.resolve({ myItem: "abc" }),
    })
})

import doWork from './worker.js';
import mockedFetch from 'node-fetch';

const originalFetch = jest.requireActual('node-fetch') as any;

test("Ensure mock", async () => {
    const result = await doWork();
    expect(result.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(1);

    const response = await originalFetch("http://www.example.org");
    expect(response.status).toBe(200);

    const result2 = await doWork();
    expect(result2.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(2);
});

AWS API Gateway IAM Authorization – Generating signature using crypto.js

I am working on an app for Jira Cloud platform using forge framework. I created an HTTP endpoint using AWS API Gateway. This endpoint triggers a lambda function that does some operation on DynamoDB. I employed IAM authorization for the endpoint. After failing trials to use aws4 library with forge, I used the following function that is taken from AWS documentation to create signing key. However, while sending the request using javascript, I always get “{message: Forbidden}”.:

export function getAWSHeaders(){
  const accessKey = ""
  const secretKey =  ""
  const regionName = "us-east-1"
  const serviceName = "execute-api"


  var date = new Date().toISOString().split('.')[0] + 'Z';
  date = date.split("-").join("").split(":").join("")
  var dateWithoutTime = date.split("T")[0]

  var myHeaders = {}
  myHeaders["X-Amz-Date"] = date;

  var crypto = require("crypto-js");

  var kDate = crypto.HmacSHA256(dateWithoutTime, "AWS4" + secretKey);
  var kRegion = crypto.HmacSHA256(regionName, kDate);
  var kService = crypto.HmacSHA256(serviceName, kRegion);
  var kSigning = crypto.HmacSHA256("aws4_request", kService);

  myHeaders["Authorization"] = "AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + dateWithoutTime + "/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + kSigning

  return myHeaders;
}

This is how I send the request:

resolver.define("test", async ({context}) => {
  var url = ""
  var myHeaders = getAWSHeaders()
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  const result = await fetch(url, requestOptions)

I cannot figure out what is wrong with my signing key generation. I checked several posts but could not find a sample request.
Thanks for the help in advance.

PS: I tested it using Postman, it works with the “AWS Signature” authorization in Postman.

Generate any number of characters random id:

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * 
 charactersLength));
   }
   return result;
}

console.log(makeid(5));

I tried to use this code but i need to generate random count of chars.

For example: “fe3jo1gl124g” or “xkqci4utda1lmbelpkm03rba”

React useEffect TypeError Method Date.prototype.toLocaleString called on incompatible receiver undefined

I know this has something to do with a problem with the function binding to the wrong “this” but I can’t figure out how to fix it. I had this issue in the useState call but fixed that by following the advice from this post, but the advice given for the .toLocaleString in the useEffect is not working. I don’t know how to resolve this. Here is my code

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function DateTime(props) {
  const [getTime, setTime] = useState(() => new Date().toLocaleString());

  useEffect(() => {
    setInterval(() => {
      setTime(new Date().toLocaleString);
    }, 1000);
  });
    return (<div className="App">{getTime}</div>);
}

Sequelize help (throw new Error(`Unrecognized datatype for attribute “${this.name}.${name}”`);)

Here is the GitHub repo for this project: https://github.com/SethZygner/full-stack-testing

I am trying to use Sequelize to use CRUD in MySQL.

    return sequelize.define("test", {
        PersonID: {
            type: Sequelize.INT
        },
        Name: {
            type: Sequelize.STRING
        }
    });
};

When I run this in the terminal with node server.js it gives me this error:
throw new Error(`Unrecognized datatype for attribute "${this.name}.${name}"`);

As well as the error Error: Unrecognized datatype for attribute "test.PersonID"

Again, I’m not sure exactly how this works given my little knowledge on using Sequelize. So the repo will be more help to get a better idea.

For reference, MySQL has a database called DB and a table within it called test

Sidebar pushes content right when minimized, sticks when maximized

I am very, very new to front-end (I’ve been doing it for a week)

I currently have some JS/React, and CSS code that makes a basic website. Everything works and I’ve fixed all the bugs but one:

When the screen is full-size, the sidebar is automatically open. I don’t really care if it is or isn’t (and my problem may be solved if it wasn’t), but it is. When I minimize, the sidebar collapses and opens as normal. The content of the main page and the navigation bar on the top push to the right using JQuery. However, if I leave the sidebar open and maximize the screen, the contents stay pushed to the right because the sidebar stays open on the larger screen.

I have no idea what you need to see to be able to help me, so I’ll post the sidebar JS and CSS and the App.js JQuery code.

App.js

  const [sidebarOpen, setsidebarOpen] = useState(false);
  const openSidebar = () => {
    setsidebarOpen(true);
    $('.main__container').toggleClass("open");
    $('.navbar').toggleClass("open");
    $('.navbar__left').toggleClass("open");
  };
  const closeSidebar = () => {
    setsidebarOpen(false);
    $('.main__container').toggleClass("open");
    $('.navbar').toggleClass("open");
    $('.navbar__left').toggleClass("open");
  };

I did try to do an if/else up there ^, something like if the sidebar is already open and you try to open again, then toggle twice, but that didn’t work.

sidebar.js

const Sidebar = ({sidebarOpen, closeSidebar}) => {
   
    return (
        <div className={sidebarOpen ? "sidebar_responsive" : ""} id="sidebar">
            <div className="sidebar__title">
                <div className="sidebar__img">
                    <img src={logo} alt="logo" />
                </div>
                <div className="sidebar__he">
                    <h1>name <br></br> stuff</h1>
                </div>
                <i
                onClick={() => closeSidebar()}
                className="fa fa-times"
                id="sidebarIcon"
                aria-hidden="true"
                ></i>
            </div>
    **menu items**

sidebar.css

#sidebar {
    background: #263f8e;
    grid-area: sidebar;
    overflow-y: auto;
    padding: 20px;
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
    height: 100vh;
  }
  
  
  .sidebar__menu > h2 {
    color: #69BF87;
    font-size: 16px;
    margin-top: 15px;
    margin-bottom: 5px;
    padding: 0 10px;
    font-weight: 700;
  }
  

  .sidebar_responsive {
    display: inline !important;
    z-index: 9999 !important;
    left: 0 !important;
    position: absolute;
    
  }
  
  @media only screen and (max-width: 978px) {
    #sidebar {
      display: none;
    }
  
    .sidebar__title > i {
      display: inline;
    }
  }

I only included what I thought might help ^^

I can’t upload an image using cloudinary

I’m using express-file upload and Cloudinary to upload a file, but not to work, here is my server file and upload file. postman is sending a 500 empty error message, postman reads all the files, but I can’t upload them on Cloudinary. I’ve tried everything I know

import express from 'express';
import cloudinary from 'cloudinary';
const router = express.Router();

cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.CLOUD_API_KEY,
    api_secret: process.env.CLOUD_API_SECRET
});

router.post('/upload', (req, res) => {
    try {
        console.log(req.files)
        if (!req.files || Object.keys(req.files).length === 0) return res.status(422).json('no files uploaded');

        const file = req.files.file;
        console.log(file);
        if (file.size > 1024 * 1024) {
            rmvTmp(file.tempFilePath);
            return res.status(400).json({ msg: 'size too large' });
        }

        if (file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
            rmvTmp(file.tempFilePath);
            return res.status(400).json({ msg: 'this file format is not supported' });
        }
        cloudinary.v2.uploader.upload(
            file.tempFilePath,
            { folder: "vireau" },
            async (err, result) => {
              if (err) throw err;
      
              rmvTmp(file.tempFilePath);
              res.json({ public_id: result.public_id, url: result.secure_url });
            }
          );
    } catch (error) {
        return res.status(500).json({ msg: error.message });
    }
});

const rmvTmp = (path) => {
    fs.unlink(path, (err) => {
      if (err) throw err;
    });
  };

export default router;

How do I prevent the anchor tag from overwriting my CSS style

I’m very new to all this. I’m trying to make my image into a link using the anchor tag but doing so seems to ignore the previous style I had for the image and I’m not sure why.
So my CSS looks like this:

/* Element */
*, *::after, *::before{
    box-sizing: border-box;
}

/* Variable */
:root{
     --handle-size: 3rem;
     --img-gap: .25rem;
}


.body{
   margin: 0;
}

.container{
   display: flex;
   justify-content: center;
   overflow: hidden;
}

.slider{
     --items-per-screen: 4;
     --slider-index: 0;
     display: flex;
     flex-grow: 1;
     margin: 0 var(--img-gap);
     transform: translateX(calc(var(--slider-index) * -100%));
     transition: transform 500ms ease-in-out;
}

.slider > img {
     flex: 0 0 calc(100% /  var(--items-per-screen));
     max-width: calc(100% / var(--items-per-screen));
     aspect-ratio: 16 / 9;
     padding: var(--img-gap);
     border-radius: 1rem;
 }

and my images are inside of a div which without the anchor displays correctly:

<div class = "slider">
    <img src="Icons/schitts.jpg" stlye="container" alt = "Schitts Creek">
    <img src="Icons/familyguy.jpg" alt = "Family Guy">
    <img src="Icons/gameofthrones.jpg" alt = "Game Of Thrones">
    <img src="Icons/sopranos.jpg" alt = "The Sopranos">
    <img src="Icons/southpark.jpg" alt = "South Park">
    <img src="Icons/prisonbreak.jpg" alt = "Prison Break">
    <img src="Icons/curbyourenthusiasm.jpg" alt = "Curb Your Enthusiasm">
    <img src="Icons/americandad.jpg" alt = "American Dad">
    <img src="Icons/sinister.jpg" alt = "Sinister">
    <img src="Icons/superbad.jpg" alt = "Superbad">
    <img src="Icons/hangover.jpg" alt = "The Hangover">
    <img src="Icons/midsommar.jpg" alt = "Midsommar">
</div>

When I add the anchor tag between an image, it ignores the previous styles I had while the other images without the anchor tag remain in the correct style.
How do I keep the layout of everything the same while allowing the image to contain a link?

Without Anchor tag

With Anchor tag around first image

onClick function calling a funciton declaration doesn’t work [duplicate]

I am trying to implement an onclick function to an html element (which results in the simulation of rolling a dice from 1 – 6) and figured out a way to that. But while I was trying to get to work, I came across a path that just wont work and I can’t figure out why.

This approach is working – I just calling methods inside the eventListener and it sucessfully returns a random number between 1 & 6 in the console:

const dice = document.querySelector('.btn--roll');     
dice.addEventListener('click', function () {
      const number = Math.trunc(Math.random() * 6) + 1;
          console.log(number);
          return number;
        });

But I just can’t figure out why the second approach is not working. I am defining a function beforehand and just calling it inside the eventListener. But the console wont print anything when I click on the button.

 function rollDice() {
      console.log(Math.trunc(Math.random() * 6) + 1);
    }
 const dice = document.querySelector('.btn--roll');
 dice.addEventListener('click', rollDice());

Material UI fill in select component based on outside source

I am writing a program that has a select field with options 1, 2, and 3. Users can choose between the 3. However another select that has an object that has a value relating to that select.

enter image description here

enter image description here

For example, if I choose ‘ten’ on the ‘Cycles’ select it is associated with an object (data) that contains a value associated with the type field. So if I select ‘Ten’, it has an object value data[‘type’] that would be 1. How can I have it so when I select a cycle option it will fill in the ‘type’ field.

              <FormControl
                sx={{ minWidth: 200 }}
                variant="standard"
                size="small"
              >
                <InputLabel>Type</InputLabel>
                <Select disabled={radioEdit}>
                  <MenuItem value="">
                    <em>None</em>
                  </MenuItem>
                  <MenuItem value={1}>1</MenuItem>
                  <MenuItem value={2}>2</MenuItem>
                  <MenuItem value={3}>3</MenuItem>
                </Select>
              </FormControl>

Here is the code I am using to declare my ‘type’ select component. The object is called data[‘type’]. How can I have that ‘type’ field empty until I select an option from ‘Cycles’ then fill it in automatically? Let me know if you need any other information, been stumped on this for awhile.

Run function before tab containing iframe(declared as web accessible resources) is closed Manifest v3

I have a manifest that looks somewhat like this:

"web_accessible_resources": [
   {
     "resources": [
       "script_injector.html",
       "script2.html"
     ],
     "matches": [
       "<all_urls>"
     ]
   }
 ],
 "content_scripts": [
   {
     "matches": [
       "<all_urls>"
     ],
     "js": [
       "new-content.js"
     ]
   }
 ],

In the new-content.js I have set an iframe:

let ifr = document.createElement('iframe');
ifr.setAttribute('allow', "microphone; camera; display-capture;");
ifr.style.display = 'none';
ifr.src = chrome.runtime.getURL('script_injector.html');
document.body.appendChild(ifr);

Script_injector.html looks like this.

<script src='script_injector.js'></script>

Script_injector.js

This file has data that needs to be saved before the tab containing the iframe is closed. The data is MediaRecorder blobs which is available only when the Mediarecorder is stopped. I need to save the data if the tab is closed and i have tried putting the save data inside the below function :

chrome.tabs.onRemoved.addListener(function (tabId, changeInfo, tab) {
savedata()
})

chrome.tabs.onRemoved is not firing at all when I close the tab. Which means the data that is recorded is lost.

Note that: I cannot use MediaRecorder in service worker in Manifest v3 because Media and Audio APIs are not allowed. So I use it this way. I am unaware about other ways but i think it’s the only method.

How do I save the data before the page containing the iframe is closed?

What would be the best practice to use JavaScript function in reactable?

In reactable it is possible to use JavaScript functions, like in this example:

reactable(iris, columns = list(
  Species = colDef(
    cell = JS("function(cellInfo) {
      return '<b>' + cellInfo.value + '</b>'
    }")
  )
))

However, all examples I saw in the documentation use string passed to the JS() function. I think that taking into account the readability and conveniences, it would be better to store the JS function in separate .js file. Is it true? And if yes, how to achieve this? I mean – how to call then this function? Based on the example above.

Why is Google Analytics and Optimize not reporting my experiment traffic?

Not sure why this isn’t working. But i have a Google Optimize experiment setup…

It changes the string in a title

The variant page loads correctly

The Optimize experiment itself connected properly to my app

I added the gtag.js script to my app through Google Tag Manager

<script type="text/javascript" id="" src="https://www.googletagmanager.com/gtag/js?id=UA-12345678-1"></script>

And

window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date);gtag("config","UA-12345678-1");

It is a custom html tag in GTM which i got warned not to do, but not sure how else to put it in.

The page is tracking as a page viewed in the main GA real time info. But when i click “View my report in Analytics” in Optimize, it takes me into GA, where there’s no hits being recorded. It’s just 0% bounces / activity.

What have i done wrong?