Move an element on another column with JavaScript

I have the following structure

<div class="container">
    <ul class="column-list">
        <li class="header-content">Header 1</li>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 2</li>
        <li>Item 2</li>
      <li>Item 2</li>
      <li>Item 2</li>
        <li class="header-content">Header 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
        <li class="header-content">Header 3</li>
        <li>Item 6</li>
    </ul>
    <div class="right"></div>
</div>

with this css:

.column-list {
    border: 1px solid black;
    column-count: 2;
    column-fill: auto;
    height: 150px;

}

.column-list li {
    break-inside: avoid;
}

.header-content {
    font-weight: bold; /* Stile per gli header */
}

.right {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

.container {
    display: flex;
    border: 1px solid blue;
    justify-content: space-between;
}

I would need that, when the “header” element has no elements printed after it in the column, it is moved directly to the next column. Is there a way to achieve this with JavaScript?

I tried with JavaScript without obtaining results

How to do I make the flip card feature work?

I’ve been trying for a while to make a flip card feature that STARTS (default) with the back face of the card and once I press the random card button I have in my form, it generates the image from the API that I have working and passes that image to the front of the card.

The PROBLEM I am having is I cannot seem to get the card to flip from the back face (default intended behavior) to the front when the button is triggered. Thus When it has been triggered again it should go back to the default state of the back of the card showing, and then it will flip back to the front with the new image again from the API. I would like to achieve this functionality.

document.getElementById("flip").onclick = function() {
  //document.getElementById("loading").style.display = "block"; // Show loading indicator
  const card = document.getElementById("card");
  card.classList.add('flipped'); // Flip the card to the back
};
/* CARD FLIP  */

.card__flip__container {
  width: 300px;
  height: 450px;
  perspective: 1000px;
}


/* .card__flip__container:hover>.card {
    cursor: pointer;
    transform: rotateY(180deg);
} */

.card {
  width: 100%;
  height: 100%;
  position: relative;
  transition: transform .4s ease-in-out;
  transform-style: preserve-3d;
}

.card-front,
.card-back {
  box-shadow: 0 0 5px 2px black;
  border-radius: 13px;
  width: 100%;
  height: 100%;
  position: absolute;
  backface-visibility: hidden;
}

.card-back {
  background-color: black;
  transform: rotateY(180deg);
}


/* Flip Effect */

.flipped .card-front {
  transform: rotateY(180deg);
  transition: all .4s ease-in-out;
  /* Flips the front out of view */
}

.flipped .card-back {
  transform: rotateY(0deg);
  transition: all .4s ease-in-out;
  /* Flips the back into view */
}
<button type="button" id="flip">Flip</button>

<!-- Card Flip Container -->
<div class="card__flip__container">
  <div class="card" id="card">
    <div class="card-image card-front">
      <!-- Front of the card (Image) -->
      <img src="<%= card.imageUrl %>" alt="<%= card.name %>">
    </div>
    <div class="card-back">
      <!-- Back of the card (Hidden when front is showing) -->
      <p>Random Card</p>
      <!-- This represents the back side of the card -->
    </div>
  </div>
</div>

min movement to move products

Basically, XXXX has its warehouses lined up in a circle, you can start from any warehouse move in either clockwise or anti-clockwise direction, the direction must remain the same throughout the remaining moves. Each warehouse stores some items. The goal is to collect excess items from some warehouses and deliver them to others need them, so that each warehouse stores the same number of items in the end (guaranteed).
The distance between 2 adjacent warehouses is 1, and the cost of each product transfer is the distance the product is moved. For example, say we have 6->6->6->3->4 (linked back to the first 6), we can optimally start from the first 6 and collect 1 item, repeat the same for the following 2 warehouses and deliver 2 to 3 and 1 to 4. In the end each warehouse has 5 items and the total cost is 1 + 2 + 3 + 1 = 7. This is just a possible clockwise move, the optimal cost should consider the anti-clockwise direction as well and return the minimum cost. I figured this was similar to LC 134 Gas Station but could not come up with a solution without using brute force.

Here is one of the comments containing sample code

The basic idea of the solution is similar to the gas station problem. We need to find a point where the balance is minimal and start moving from the point next to it. It looks like the total cost can be calculated in 1 pass. Then repeat for moving in the opposite direction and compare the results.

Imagine a chart showing the current balance. The shape of the chart does not depend on the choice of the starting point of the route. This choice only raises or lowers the chart relative to the Y axis. If we choose the starting point as I described earlier, the balance will never go below 0. At each point it will be increased by -minBalance. So we can just add -n*minBalance at the very end.

int getCost(const int n, const vector<int>& a, const int target) {
    int cost = 0, balance = 0, minBalance = 0;
    for (const auto x : a) {
        balance += x - target;
        minBalance = min(minBalance, balance);
        cost += balance;
    }
    return cost - minBalance * n;
}

int solve(vector<int>& a) {
    const int n = (int)a.size(), target = reduce(a.cbegin(), a.cend()) / n;
    const int cw = getCost(n, a, target);
    ranges::reverse(a);
    const int ccw = getCost(n, a, target);
    return min(cw, ccw);
}

int main() {
    vector a {6,6,6,4,3};
    cout << solve(a) << endl; // 7
}

There a few lines which I don’t understand

balance += x – target;

x - target means the diff at each point, to reach balance, why do we need to accumulate them?

minBalance = min(minBalance, balance); why do we need to find out he minBalance?

cost += balance; balance1 = point1, balance2 = point1 + point2, balanceN = point1 + ..pointN. Why is this “cost”?

cost - minBalance * n? What is minBalance*n? Why do we take it off from cost?

I did try to come up with my own solution, but it did not work.

const ans = (inarr) => {
    let arr = [];

    const sum = inarr.reduce((item, all) => {
        return item + all;
    }, 0) / inarr.length;

    // * g: convert to new arr
    for (let i = 0; i < inarr.length; ++i) {
        const ele = inarr[i];
        const diff = ele - sum;
        arr.push(diff);
    }

    // * g: arr = [-2, -1, 1, 1, 1]
    const scan = (local_arr) => {
        let total = 0;

        // * g: forward looking
        for (let i = 0; i < local_arr.length; ++i) {
            if (local_arr[i] === 0 || local_arr[i] < 0) {
                continue;
            }

            // * g: it is positive now

            // * g: 1. double the arr
            // * g: 2. double the ind, but not arr
            // * g: 3. the double arr ind has own range, but need mod to access origin arr
            let j = i + 1;
            while (j < i + inarr.length) {
                const i_ind = j % inarr.length;
                // * g: we don't want >= 0
                if (local_arr[i_ind] > 0 || local_arr[i_ind] === 0) {
                    ++j;
                    continue;
                }

                // * g: it is now negative; the i need to share some positive energy to it

                // * g: 1. full balance
                // * g: 2. partial balance
                // * g: 3. how much to give out; how much to absort;
                //
                // * g: local_arr[i] -> local_arr[i_ind]

                // * g: 1. |a| <= |b|; a give all; a become zero; b update; but a finish
                // * g: 2. |a| > |b|; b absort all; b become zero; a update; but a still not finish
                if (Math.abs(local_arr[i]) <= Math.abs(local_arr[i_ind])) {
                    total = total + Math.abs(i_ind - i);
                    local_arr[i_ind] = local_arr[i_ind] + local_arr[i];
                    local_arr[i] = 0;
                    break;
                } else {
                    total = total + Math.abs(i_ind - i);
                    local_arr[i] = local_arr[i] + local_arr[i_ind];
                    local_arr[i_ind] = 0;
                }

                ++j;
            }
        }

        return total;
    }


    let min = Infinity;
    for (let i = 0; i < inarr.length; ++i) {
        // * g: backup
        const arr1 = arr.slice(0);
        const arr2 = arr.slice(0);

        // * g: forward scan; arr destroy
        const o1 = scan(arr1);

        // * g: backward scan; arr1 destroy
        const o2 = scan(arr2);

        // * g: min
        min = Math.min(min, o1, o2);

        // * g: 1st ele to end
        arr.push(arr.shift());
    }

    return min;
}

// const in_arr = [3, 4, 6, 6, 6];
const in_arr = [6, 6, 6, 3, 4];
const out = ans(in_arr);
console.log(out)

original: https://leetcode.com/discuss/interview-question/5834906/amazon-new-grad-oa/2648819

What aria attributes to be used in a dropdown that has filters button (which is a custom Lit component) and how to handle its accessibility?

The dropdown has a search input and filter such as All, Volume, Trend, Momentum, these filters are created in a custom component. On select of dropdown the focus is on search box and on click of arrow down I traverse the list items. And on click of tab we move across filters buttons, and on click of enter/space the list items are filtered. But when the focus is on filters and I arrow down to traverse through the list of items , those items are not displayed on screen reader.
May i know how can i resolve this issue of accessibility?
Dropdown image

 Have tried using aria-activedescendant and aria-owns but none worked, just to note that my       filters  are in custom component and i render it in my main dropdown component.

How to make sure that i get the list items displayed on the screen when the focus is on filter??

 serach box code in dropdown component :
 <div class="indicator-search" @keydown=${this.trackKeyboard}>
 <input
 id="indicator-input"
 type="text"
 autocomplete="off"
 aria-label="search indicators"
 aria-controls="indicators-list"
 aria-activedescendant=${activeDescendant}
@input=${this.searchIndicators}>
</div>


Button-group used in dropdown component:
<div
@keydown=${this.trackKeyboard}
@keyup=${this.onKeyUp}>
<button-group
.options=${this.indicatorTypeList}
 @change-input=${this.toggleIndicatorTypes}>
</button-group>
</div>`

Dropdown component list items code:
<ul 
@keydown=${this.trackKeyboard}
@keyup=${this.onKeyUp}
id="indicators-list" 
class="list-reset" 
role="listbox"
tabindex="0"
aria-multiselectable="true" 
aria-label="indicators"
aria-activedescendant=${activeDescendant}>
 this.indicatorOptions.map((item, index) => {
            return html`
                      <li
                        id="${item.id}-option"
                        class="indicator-option ${classMap({ focus: index === focusIndex })}"
                        role="option"
                        aria-selected=${index === focusIndex}
                        @click=${() => this.onOptionClick(item)}>
                        ${item.displayName}
                      </li>`;
          })      
 </ul>

Login with google button blinks

I develop a frontend application with vue-3, and need to implement login with google.
I managed to have the entire flow working, but there is one thing that really annoys me, that the button blinks an instance after the page is loaded:

Google sign in button blinking

This is my simplified code:

<template>
  <div>
    <div style="height: 44px; width: 250px">
      <div id="g_id_onload"
           :data-client_id="googleClientId"
           data-callback="handleGoogleCredentialResponse"
           data-auto_prompt="false"></div>
      <div class="g_id_signin" data-type="standard"></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      googleClientId: import.meta.env.VITE_API_GOOGLE_CLIENT_ID,
    };
  },
  mounted() {
    this.loadGoogleSdk();

  },
  methods: {
    // Load the Google SDK and render the button
    loadGoogleSdk() {
      const script = document.createElement('script');
      script.src = 'https://accounts.google.com/gsi/client';

      script.onload = () => {
        google.accounts.id.initialize({
          client_id: this.googleClientId,
          callback: this.handleGoogleCredentialResponse,
        });
        google.accounts.id.renderButton(
            document.querySelector('.g_id_signin'),
            {theme: 'outline', size: 'large', shape: 'pill'}
        );
      };
      document.head.appendChild(script);
    },
  },
};
</script>

Any idea how to solve this problem?

Angular: Module not found error from external js file

In my angular project, I added an external js file src/app/example.js and a typescript file src/app/example.d.ts. In the typescript file added export const getUpdate: () => {};

Now I get bunch of module not found error for example Module not found: Error: Can't resolve 'jquery-mousewheel' that comes from the example.js file. Is there a way to ignore all the errors from this external js file or any external js file?

Iterating Properties in Object Oriented JavaScript

I am trying to develop a more object oriented approach to my programming but have run into a problem. I thought it would be useful to group related properties in an object together with methods that operate on the properties.

An example of this would be an object holding some properties with strings as values together with a method that can iterate over all of the (non-method) properties changing them to uppercase.

const myObj = {
  prop1: "one",
  prop2: "two",
  myMethod: function() {
    Object.keys(this).forEach(prop => {
      if (typeof this[prop] !== "function"){
        this[prop] = this[prop].toUpperCase();
      }
    });
  },
}

console.log(myObj.prop1, myObj.prop2);
myObj.myMethod();
console.log(myObj.prop1, myObj.prop2);

I would be happy with this if it was not for the need to have a conditional clause, if (typeof this[prop] !== "function"){...}, in order to prevent the method working on methods as well as properties. Although the conditional clause does work in this case you might have a case where you have some methods which you want other methods to operate on and there is a distinction (for you) between the methods you want to be operated on and those that do the operating.

One way around using the conditional would be to put the properties you want to be acted on inside another object but then that means that when you use them you have a more complicated way of referencing them:

const myObj = {
  props: {
    prop1: "one",
    prop2: "two",
  }
  myMethod: function() { ... }
    });
  },
}

Now I would have to reference the properties as myObj.props.prop1 instead of myObj.prop1 which looks much better to me.

I was wondering whether there is some common satisfactory way of addressing this issue and what other people think about it.

Image onload just loads first image in array

I need to get the width and height of som media (images and videos).
I am using a for loop and onload/eventlistner to get this, but if I have more then one media of the same kind, I only get the data of the first one. (I have to use old javascript so no foreach)

for (var i = 0; i < length; i++) {
  if (screen.backgroundMedia.type === "photo") {
    var img = new Image();
    img.onload = function() {
       console.log(this); // this just shows for the first image in the list whith two images
     };
  }

Better way to filter an array of objects with one constant and one always changing value

I am currently looking for a better way to filter my array of objects to avoid duplicate my code again and again.

Here is my example array:

arr = [
{
"no": 11145,
"stringers": "P1",
"ribs": "R1",
"description": "some text"
},
{
"no": 14568,
"stringers": "P1",
"ribs": "R1",
"description": "some text"
},
{
"no": 24562,
"stringers": "P2",
"ribs": "R9",
"description": "some text"
},
{
"no": 658741,
"stringers": "P1",
"ribs": "R2",
"description": "some text"
},
{
"no": 325690,
"stringers": "P4",
"ribs": "R5",
"description": "some text"
},
{
"no": 9745201,
"stringers": "P1",
"ribs": "R2",
"description": "some text"
},
.....
]

Currently I am filtering the array like that:

let p1r1 = arr.filter(function(el){
  return el.stringers === "P1" && el.ribs === "R1"
})
let p1r2 = arr.filter(function(el){
  return el.stringers === "P1" && el.ribs === "R2"
})
// ...and so on

This results in a lot of lines where I repeat the same code over and over (except for the changing ribs value). Is there a more elegant way to solve this?

Pass frontmatter variables to scripts using data-attribute and use in JavaScript Class

I have the following Astro component:

   ---
    type Props = {
      uuid: string;
    };
    
    const { uuid } = Astro.props;
    ---
    
    <div class="my-feature" data-uuid={uuid} id="my-feature"></div>
    
    <script is:inline src={import.meta.env.MY_SCRIPT}></script>
    
    <script>
      import { MyFeatureHelper } from '@/scripts/my-helper';
    
      let myFeature;
    
      const ref = document.getElementById('my-container');
    
      myFeature = new MyFeatureHelper(ref as HTMLDivElement, {
        uuid: this?.ref.uuid,
      });
    
      myFeaturer.build();
    
    </script>

I need to pass uuid prop to the <script> tag without define:vars as described here because then my script will be treated as is:inline and I can’t import the JavaScript Class MyFeatureHelper, which I need.

How can I get access to uuid and use it like e.g. uuid: this?.ref.uuid, using the data-attribute trick?

How do I get this to work?

Astro ass frontmatter variables to scripts using data-attribute and use in JavaScript Class

I have the following Astro component:

   ---
    type Props = {
      uuid: string;
    };
    
    const { uuid } = Astro.props;
    ---
    
    <div class="my-feature" data-uuid={uuid} id="my-feature"></div>
    
    <script is:inline src={import.meta.env.MY_SCRIPT}></script>
    
    <script>
      import { MyFeatureHelper } from '@/scripts/my-helper';
    
      let myFeature;
    
      const ref = document.getElementById('my-container');
    
      myFeature = new MyFeatureHelper(ref as HTMLDivElement, {
        uuid: this?.ref.uuid,
      });
    
      myFeaturer.build();
    
    </script>

I need to pass uuid prop to the <script> tag without define:vars as described here because then my script will be treated as is:inline and I can’t import the JavaScript Class MyFeatureHelper, which I need.

How can I get access to uuid and use it like e.g. uuid: this?.ref.uuid, using the data-attribute trick?

How do I get this to work?

Fill an Array in js file [duplicate]

i use this code to fill reviewArray, but it’s not getting filled in the right position.

getSuccessOutput();
function getSuccessOutput() {
    $.ajax({
        type: "post",
        url: 'RetMetriseis.php',
        dataType: "json",
        success: function (data) { //start success            
            var oldString = JSON.stringify(data);
            var laststring;            
            oldString = oldString.replace('{"result":', "");
            laststring = oldString.slice(0, oldString.length - 1);
            console.log(laststring);
            this.searchData = JSON.parse(laststring);
            console.log(searchData);
            reviewArray=( JSON.parse(laststring));
            console.log(reviewArray);

            comboBoxObject.datasource = reviewArray;
            comboBoxObject.dataBind();
            return;
        },
        error: function () {
            alert('There was some error performing the AJAX call!');
        }
    });
    //return false;
}
let comboBoxObject = new ej.dropdowns.ComboBox({
    // bind the country data to dataSource property

    dataSource: reviewArray,
    // maps the appropriate column to fields property
    fields: {
        text: "ptype",
        value: "id"
    },
    //set the placeholder to ComboBox input
    placeholder: "Select something",
    //enable the autofill property to fill a first matched value in input when press a down key
    autofill: true
});
comboBoxObject.appendTo('#comboelement');

i need reviewArray to fill comboBoxObject but getSuccessOutput() function runs lastly!
Any suggestion?

How to install react on github repo remotely from a node server?

I have a project with a client and server side. On the client-side, users get authenticated in github, and then select a template thumbnail, and then we sent a token and the template details to the node service side, where a new repository is generated in github. So, far, I have created this pipeline and it works fine. A new repo is generated, but it’s empty.. I need react to be installed in the newly generated repository, but I can’t make it work.

This is the relevant function in my node server that generates the repo:

async function createRepository(authAccessToken, repositoryName, repositoryDescription, repositoryFramework, templateName) { 
  const accessToken = authAccessToken;
  const repoName = repositoryName;
  const repoDescription = repositoryDescription;
  const repoFramework = repositoryFramework;
  console.log(templateName, repoFramework)

  const headers = {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json'
  };
  
  const data = {
    'name': repoName,
    'description': repoDescription,
    'private': false
  };
  
  const response = fetch('https://api.github.com/user/repos', {
    method: 'POST',
    headers,
    body: JSON.stringify(data)
  })
  .then(response => response.json())
  .then(data => {
    if(data.html_url) { 
      console.log(`Repository created: ${data.html_url}`)
      return data.html_url;
    } else {
      console.log('Failed to generate repository')
      return null;
    }
  })
  .catch(error => console.error(`Error creating repository: ${error}`));

  if(response) { 
    return response;
  } else { 
    return null;
  }
}

I have tried several things:

I tried adding this:

const repoDir = `./${repoName}`;
  fs.mkdirSync(repoDir);
  
  exec(`cd ${repoDir} && npx create-react-app ./`, (error, stdout, stderr) => {
    if (error) {
      
      return null;
    }

  });

It didn’t work.

I tried:
console.log(‘Creating React app…’);
await runCommand(‘npm’, [‘exec’, ‘create-react-app’, ‘.’], { cwd: repoDir });
console.log(‘React app created successfully.’);

Also didn’t work..
I tried a few other similar adjustments, but it doesn’t work. For some I would get an error like: Error: spawn npm ENOENT.. for others I don’t get any errors, the repo is just empty..

I tried increasing the time of the exec() so it doesn’t time out while react is being generated, but it seems that the server restarts after a few seconds after exec() is invoked.. not really sure what is the problem, and if the timing out is the problem.

How to print the full, updated array after removing the last object?

I’m currently making a website with a “shopping list” functionality. I can create an array and add items to the “shopping list” via the input field, and I can also remove the latest input using a button.
As of now, the list shows all new items in order of input. But, when I remove the latest item, it shows only that item. And then when I add a new item, the full, updated list shows.

These pictures show how it currently looks:

  1. Add items, that show up in the list ยจ
    enter image description here
  2. Remove item – the list disappears and only the latest item being removed is shown
    enter image description here
  3. The new, updated list shows ONLY after I’ve added a new item to the list (“four”)
    enter image description here

What I’m trying to do is this:

  1. Add items – they show up in the list, as now
    enter image description here
  2. Remove item – the latest item is just removed from the list, but the list still shows previous items remaining. The picture here is how I want it to look.

enter image description here

  1. Add new items again – they get added to the list in order of input as it looks in the picture.
    enter image description here
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');

function addWord() {
  errorElement.innerHTML = "";
  var word = inputElement.value;
  if (word.trim() === "")
    errorElement.innerHTML = "Empty input, write an item you want to put on the list!";
  else
    arrayOfWord.push(word);
  inputElement.value = "";
  process();
}

function process() {
  words.innerHTML = arrayOfWord.join(' <br><br> ');
}

function remove() {
  words.innerHTML = arrayOfWord.pop();
  document.getElementById('words').innerHTML = parsed;
}
<p>
  <ol id="demo"></ol>
</p>

<input id="userinput" /><button onclick="addWord()">Add item</button>
<div id="error"></div>
<button onclick="remove()">Remove</button><br>

<p id="testing"></p>
<p id="words"></p><br>

<a href="#" class="action">Buy Now</a>
</div>

How can I bias output signal in Web Audio API?

I’m trying to make some audio signals with web audio API. And I want to add some bias to my audio signal in web/js. How can I bias up/down audio signal like this image?

image from https://www.csounds.com/tootsother/east/Bias/Bias.html

I made some oscillators and I couldn’t find clues in my searching ability.

  const ac = new AudioContext();

  const leftOsc = ac.createOscillator();
  const leftGain = ac.createGain();
  const rightOsc = ac.createOscillator();
  const rightGain = ac.createGain();
  const merger = ac.createChannelMerger(2);

  leftOsc.connect(leftGain);
  leftGain.connect(merger, 0, 0);
  rightOsc.connect(rightGain);
  rightGain.connect(merger, 0, 1);

  leftOsc.type = 'sine';
  leftOsc.frequency.value = 440;
  leftGain.gain.value = 0.5;
  leftOsc.start();

  rightOsc.type = 'sine';
  rightOsc.frequency.value = 440;
  rightGain.gain.value = 0.5;
  rightOsc.start();

  merger.connect(ac.destination);