Alpine.js and how to render row numbers on a table with nested x-for

I am stuck trying to assign row number for a table.
The rendered “rowNumber” on each row have wrong values.

this is the example code: https://jsfiddle.net/erxwjmts/2/

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alpine.js v3.x Ejemplo</title>
    <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">
  </head>

  <body class="p-m" x-data="componentData">


    <table class="table table-bordered table-responsive table-hover m-t-md">
      <thead>
        <tr>
          <th> Number </th>
          <th> Sample Field </th>
          <th> Indexes </th>
        </tr>
      </thead>
      <tbody>
        <template x-for="(group1, index1) in arrayGroup1" :key="index1">
          <template x-for="(group2, index2) in group1.arrayGroup2" :key="index2">
            <template x-for="(group3, index3) in group2.arrayGroup3" :key="index3">
              <template x-for="(group4, index4 ) in group3.arrayGroup4" :key="index4">
                <tr>
                  <td>
                    row number:
                    <span x-text="rowNumber++"></span>
                  </td>
                  <td>
                    <span x-text="group4.location"></span>
                  </td>
                  <td>
                    <div x-text="'index1:' + index1"></div>
                    <div x-text="'index2:' + index2"></div>
                    <div x-text="'index3:' + index3"></div>
                    <div x-text="'index4:' + index4"></div>
                  </td>
                </tr>
              </template>
            </template>
          </template>
        </template>
      </tbody>
    </table>


  </body>

</html>

and the js script

<script>
document.addEventListener('alpine:init', () => {
  Alpine.data('componentData', () => ({
    "rowNumber": 0,
    "arrayGroup1": [{
        "id": 684,
        "formalName": "TRADING COMPANY NORTHERN ROSES LLC",
        "arrayGroup2": [{
            "nickName": "no-nickName",
            "arrayGroup3": [{
              "sid": "cid_11527",
              "type": "TypeOne",
              "id": 11527,
              "arrayGroup4": [{
                  "location": "ESSAY LIVE, JOHN DOE, PLACE: SUGAR LOAF",
                  "samples": [{
                      "date": "2023-06-23",
                      "id": 66357
                    },
                    {
                      "date": "2023-06-23",
                      "id": 66356
                    }
                  ]
                },
                {
                  "location": "ESTATE FUTACUIN ROUTE 215 KM 60- PUYEHUE",
                  "samples": [{
                    "date": "2023-06-23",
                    "id": 66354
                  }]
                }
              ]
            }]
          },
          {
            "nickName": "John What",
            "arrayGroup3": [{
              "sid": "cid_11339",
              "type": "TypeOne",
              "id": 11339,
              "arrayGroup4": [{
                "location": "SOME LOCATION BETWEEN STATES",
                "samples": [{
                  "date": "2023-06-23",
                  "id": 66355
                }]
              }]
            }]
          }
        ]
      },
      {
        "id": 4556,
        "formalName": "JOHN DOE SMITH JOHNSON",
        "arrayGroup2": [{
          "nickName": "no-nickName",
          "arrayGroup3": [{
              "sid": "pid_1707",
              "type": "TypeTwo",
              "id": 1707,
              "arrayGroup4": [{
                "location": "THE APPLE ORCHARD, SAINT CHARLES",
                "samples": [{
                  "date": "2023-06-23",
                  "id": 66347
                }]
              }]
            },
            {
              "sid": "cid_11577",
              "type": "TypeOne",
              "id": 11577,
              "arrayGroup4": [{
                "location": "ROSE FLOWER, SAINT DOMINGO VALLEY",
                "samples": [{
                  "date": "2023-06-22",
                  "id": 66346
                }]
              }]
            }
          ]
        }]
      }
    ]
  }));
});
</script>

I get this advice from github: “Just put elements between the layers that have display: content Or fix your data.” But sorry I don’t understood that or how to fix it.

for now I use CSS counters, but it is not the ideal.

thanks

How can I refresh the page during a function running?

I have a project running with browser-side JavaScript and HTML.

I have a button that causes a computation-heavy function to run, which could take minutes to run. I run the function from the button like this: <button onclick=`longFunction()`>run</button>.

While the function is running, the page is inactive, and the only way I have found to provide data during the function running is console.log(), which is not ideal, since I want to show progress in the task while it’s running (i.e. show percentage completed of the function).

I tried to find some method to refresh the screen so that the changes I made through setting innerHTML show up while the function is running, but I couldn’t find anything.

Is there any such method? And what would you recommend generally in this scenario?

When I run vercel, I get a build failure. I don’t know why I can’t find the package.json file

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /vercel/path0/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open ‘/vercel/path0/package.json’
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in: /vercel/.npm/_logs/2024-01-21T08_54_38_854Z-debug-0.log
Error: Command “npm install” exited with 254

Hopefully the build will be successful

How to insert a svg image marker inside canvas image

I have a problem to solve. In my canvas image I put a marker but this is image type “png”, I would like to have an icon svg so I can change the colour.

This code is working, i need to change .png with .svg, but doesn’t work.

var Marker = function () {

    this.Sprite = new Image();
    this.Sprite.src="http://www.clker.com/cliparts/w/O/e/P/x/i/map-marker-hi.png";
    this.Width = 20;
    this.Height = 32;
    this.XPos = 0;
    this.YPos = 0;
    this.textarea=null;
}

enter image description here

Pie Radial Menu Vue.js

I have a radial menu where I implemented automatic positioning of elements in a circle. However, I’m having issues with the arrangement of these elements. I want to display them as pie slices, but I’m struggling to replicate this. Does anyone have any ideas on how to achieve this?

<template>
    <div class="wrapper">
        <ul class="radial">
            <li v-for="(navItem, index) in navItems" :key="index" :class="'button-' + index" ref="navItems">
                <a href="#">
                    <div class="button-inner">
                        <img src="" alt="">
                        <p>{{ navItem.label }}</p>
                    </div>
                </a>
            </li>
            <div class="radial-inner">
                <p class="radial-inner__title" id="hovered"></p>
                <div class="radial-inner__subtitle">
                    CLICK
                    <img src="" alt="">
                </div>
            </div>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            navItems: [
                { label: 'Item 1' },
                { label: 'Item 2' },
            ],
            radius: 340,
        };
    },
    mounted() {
        this.positionNavItems();
    },
    methods: {
        positionNavItems() {
            const theta = (2 * Math.PI) / this.navItems.length;
            const offset = Math.PI / 2 + theta;

            this.navItems.forEach((_, index) => {
                const currentAngle = index * theta + offset;
                const xPosition = this.radius * Math.cos(currentAngle);
                const yPosition = this.radius * Math.sin(currentAngle);

                this.$refs.navItems[index].style.transform = `translate(-50%, -50%) translate(${xPosition}px, ${yPosition}px)`;
            });
        },
    },
};
</script>
  
<style lang="scss">
.wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000;
}

.radial {
    width: 830px;
    height: 830px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    border-radius: 50%;

    &-inner {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 3;
        width: 515px;
        height: 515px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        &__title {
            color: #FFF;
            font-family: Akrobat, sans-serif;
            font-size: 60px;
            font-weight: 800;
            text-transform: uppercase;
        }

        &__subtitle {
            display: flex;
            align-items: center;
            color: #FFF;
            font-family: Akrobat, sans-serif;
            font-size: 28px;
            font-style: normal;
            font-weight: 800;

            img {
                width: 35px;
                height: 47px;
                margin-right: 5px;
                margin-left: 5px;
            }
        }
    }


    li {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        clip-path: polygon(50% 0% 100%, 100% 100%);
        filter: blur(0);
        overflow: hidden;
        z-index: 1;
        transition: all 0.3s;

        &:hover {
            background: #FFBA09;
        }

        a {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: inherit;

            img {
                width: 90px;
                height: 90px;
            }
        }
    }

    &:before {
        position: absolute;
        top: 50%;
        left: 50%;
        content: "";
        display: block;
        width: 515px;
        height: 515px;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        background: #161616;
        box-sizing: border-box;
        z-index: 2;
    }
}

.button-inner {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    p {
        font-family: 'Akrobat', sans-serif;
        text-decoration: none;
        color: #CFCFCF;
        font-size: 22px;
        font-style: normal;
        font-weight: 800;
        text-transform: uppercase;
        max-width: 120px;
        text-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
        margin-top: 10px;
    }
}
</style>

I would appreciate your help.

Changing color dots to show what currently is showing on the page

I have section where I show most recently news. I’m using arrows to scroll throught these news. I wanted to add some dots to show the users on which text they’re on. I want for active dot to change color and it’s working but only when I’m going forward. When I want to go back to the previous news, same dot stay active. How can I fix that?

document.addEventListener("DOMContentLoaded", function() {
  const dotsContainer = document.getElementById("dots");
  const scrollText = document.getElementById("bannerText");

  for (let i = 0; i < scrollText.children.length; i++) {
    const dot = document.createElement("div");
    dot.classList.add("dot");
    dotsContainer.appendChild(dot);
    dot.addEventListener("click", function() {
      scrollToChild(i);
    });
  }

  let currentIndex = 0;

  window.scrollLeft = function() {
    if (currentIndex > 0) {
      currentIndex--;
    } else {
      currentIndex = scrollText.children.length - 1;
    }
    scrollToChild(currentIndex);
  };

  window.scrollRight = function() {
    if (currentIndex < scrollText.children.length - 1) {
      currentIndex++;
    } else {
      currentIndex = 0;
    }
    scrollToChild(currentIndex);
  };

  let isArrowScroll = false;
  scrollText.addEventListener("scroll", function() {
    if (isArrowScroll) {
      const childIndex = Math.round(scrollText.scrollTop /
        scrollText.children[0].offsetHeight);
      currentIndex = childIndex;
      updateDots();
    }
  });


  function scrollToChild(index) {
    currentIndex = index;
    updateDots();
    const child = scrollText.children[index];
    scrollText.scrollTo({
      top: child.offsetTop,
      behavior: "smooth"
    });
  }

  function updateDots() {
    const dots = dotsContainer.querySelectorAll(".dot");
    dots.forEach((dot, index) => {
      if (index === currentIndex) {
        dot.classList.add("active");
      } else {
        dot.classList.remove("active");
      }
    });
  }

  window.addEventListener("keydown", function(event) {
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      isArrowScroll = true;
    }
  });

  scrollText.addEventListener("scrollend", function() {
    isArrowScroll = false;
  });

  updateDots();
});
<div class="a0">
  <div class="color">
    <div class="title">
      <span class="text-item1">News</span>
    </div>
    <div class="news">
      <div class="cover">
        <button id="scroll-left" class="icon" onclick="scrollLeft()"><i class="fa-solid fa-angles-left"></i></i></button>

        <div class="scroll-text" id="bannerText">
          <div class="child">text1</div>
          <div class="child">text2</div>
          <div class="child">text3</div>
          <div class="child">text4</div>
        </div>
        <button id="scroll-right" class="icon" onclick="scrollRight()"><i     class="fa-solid fa-angles-right"></i></button>
      </div>

    </div>
    <div id="dots" class="dots-container"></div>
  </div>
</div>

Is there an effective library for removing unused JavaScript and CSS from HTML files with all style and script inlined?

I am currently working with a large database of front-end code that i have to clean and prepare for data analysis. In scraping these sites however, a lot of redundant CSS and JS was collected alongside the relevant code. The database system i am using is currently sqlite, so i mostly use python for data editing. I am however open to solutions using other languages.

I seem to be unable to find any python libraries that can help me automate the removal of unused CSS and JS. I see that there is a JS extention called purifyCSS, however, this setup requires separated CSS and HTML files present in a local environment (i.e., cannot handle strings, parsed html in code or inlined HTML files).

Am i just bad at looking, or is there no other more effective way of removing unused JS and CSS?

I have like 10gb of html files that i have to clean, so having a more effective solution than creating temp files would be desirable.

How to use onAuthStateChange in multiple js files with webpack

I’m trying to use onAuthStateChange from firebase authentication to get the information about the user currently logged in, in order to get a document in my Firestore database (that contains all the informations about the selected user).

At, I started by doing it on my header.js that contains the header used everywhere across my app, and I was doing DOM modifications directly in the function, like this example:

let userData = "";

onAuthStateChanged(auth, async (user) => {
    if (user) {
        console.log(user);
        const userDoc = await getDoc(doc(db, "users", user.uid));
        userData = { uid: userDoc.id, ...userDoc.data() };
        elements.userFirstname.textContent = userData.firstname;
    } else {
        elements.loginButton.style.display = "block";
        elements.userDropdown.style.display = "none";
    }
});

But this is not scalable at all, because I have user content to display also in the body of the page. So I’m thinking to make userData a global variable that I can re-use everywhere by doing an import. However, the import is made far before onAuthStateChanged is done.

This seems to be a recurrent thing people needs when using Firebase authentication, however I don’t find any explanations on how to do it properly.

JQuery Ajax doesn’t work in external local file

I have this file called index.html, where I have included JQuery and then, in a javascript , I have called the function roundabout() from the file JSrequest.js:

$(document).ready(function()
{
    console.log("test");
});

function roundabout()
{
    var overpassQuery = '[out:json][timeout:100000];(area[name="Siena"][admin_level=6];)->.province;way["junction"="roundabout"](area.province);node["highway"="mini_roundabout"](area.province);out geom;';
    $.ajax(
    {
        url: 'https://overpass-api.de/api/interpreter',
        data:
        {
            data: overpassQuery
        },
        type: 'GET',
        dataType: 'json',
        success: function(data)
        {
            // Decode OSM data into coordinates, stored in 2 arrays
            var features = data.elements;
            var lats = [features.length];
            var lngs = [features.length];
            for (var i = 0; i < features.length; i++)
            {
                lats[i] = features[i]["lat"];
                lngs[i] = features[i]["lon"];
            }
            return lats[0];
        },
        error: function(error)
        {
            return error;
        }
    });
}

The “test” output works, meaning that JQuery is working, but the success and error functions of the ajax doesn’t work, while if I put the same exact functions in a inline into the index.html file, it works. This files are stored locally and not on a server.
I checked with a web debugger that the request works, and it actually does, but the functions success or error never get called

How can use vue autonumeric input mask in nuxt3?

I need input mask for money inputs and phone number inputs.

I tried this vue package and couldn’t install it to nuxt3

https://github.com/autoNumeric/vue-autoNumeric/tree/master

I defined nuxt3 plugin in my plugins/moneyMask.js file

import {VueAutonumeric} from 'vue-autonumeric/dist/vue-autonumeric.min.js'

export default defineNuxtPlugin((nuxtApp) => {
 nuxtApp.vueApp.component('VueAutonumeric', VueAutonumeric);
})

and used in template

            <VueAutonumeric
                class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                v-model="contract.monthly_rent"
                :options="'commaDecimalCharDotSeparator'"
            ></VueAutonumeric>

but fails:

[Vue warn]: Failed to resolve component: VueAutonumeric
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.

Add two arrays with nested components into a new ‘combined’ array

I’m trying to combine two arrays with nested components into a new array. Best explained with example:

InputValues1 = [{"Values": [{"Input1": 1, "Input2": -1}, {"Input1": 1, "Input2": -2}, {"Input1": 2, "Input2": -2}, {"Input1": 4, "Input2": -4}], "Name": "AA", "key": 1}, {"Values": [{"Input1": 1, "Input2": -2}, {"Input1": 3, "Input2": 5}, {"Input1": 3, "Input2": 2}, {"Input1": 1, "Input2": -2}], "Name": "AB", "key": 2}]

InputValues2 =  [{"Values": [{"Input1": 3, "Input2": 2}, {"Input1": 2, "Input2": 1}, {"Input1": 1, "Input2": 1}, {"Input1": 1, "Input2": 6}], "Name": "BA", "key": 1}, {"Values": [{"Input1": 30, "Input2": 1}, {"Input1": 6, "Input2": 2}, {"Input1": 1, "Input2": 2}, {"Input1": 1, "Input2": 8}], "Name": "BB", "key": 2}]

The new combined output needs to be:

CombinedOutput = [{"Values": [{"Input1": 4, "Input2": 1}, {"Input1": 3, "Input2": -1}, {"Input1": 3, "Input2": -1}, {"Input1": 5, "Input2": 2}], "Name": "AABA", "key": 11}, {"Values": [{"Input1": 31, "Input2": -1}, {"Input1": 9, "Input2": 7}, {"Input1": 4, "Input2": 4}, {"Input1": 2, "Input2": 6}], "Name": "ABBB", "key": 22}]

So I’m looking to sum the nested Values arrays together, and concatenate the Name and key values.

I’m thinking the map function might be useful here, but I’m a little lost as to how to deal with the nested aspect as well as not create a mess with for loops.

I’ve shown the InputValues as having 2 entries each, but this could be larger, so I’m worried about my crude thinking of for loops.

Uncaught ReferenceError: jwt_decode is not defined

I am working on a project and am stuck at this part where i am trying to retrieve the profile information on the account im currently logged into using the token. While using the JWT-decoding library i am constantly faced with the issue of jwt_decode is not defined. will need some guidance

I have tried using require but that did not work as well, import will not be usable as i am not using esm. I have also included the cdn to jwt_decode in my html file but its still not working

here is the relevant code in my html and js in 2 different files:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jwt-decode.min.js"></script>

const authToken = localStorage.getItem("token"); // Retrieve authToken from localStorage
const decodedToken = jwt_decode(authToken); // Change jwtDecode to jwt_decode
const user_id = decodedToken.user_id;

fetchMethod(currentUrl + `/api/users/${user_id}`, callback, "GET");

error in my browser console

Uncaught ReferenceError: jwt_decode is not defined
    at profile.js:2:22