How to target this button in the if condition in vanilla javascript

I have several buttons with the same class that toggle dropdown lists, the lists are closed if the user clicks somewhere outside the button, but if the user clicks on the other button with the same class, the list belonging to the previously clicked button stays open, how can I change this so that if the user clicks on any other button other than “this” – the other list closes? (What I’m trying to do is to change the if condition to something like if (!event.target.matches this (‘.dropdown-btn’)) )

<button onclick="myFunction(this)" class="dropdown-btn">
    Pirkt tiešsaistē
    </button>
    <div class="dropdown-list">
      ...
    </div>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(obj) {
  obj.classList.toggle("dropdown-btn-active");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropdown-btn')) {
    var dropdownBtns = document.getElementsByClassName("dropdown-btn");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('dropdown-show')) {
        openDropdown.classList.remove('dropdown-show');
      }      
    }
}

Knex.js update function saving as [object Object] in SQLite database instead of stringified JSON

I have Knex.js setup with an SQLite database. When I create an entry via the insert function, it correctly converts the JSON fields into strings. When updating using the update function, it inserts [object Object] into the database column instead.

For example, say we have the table card with columns id (int), name (string), and service (string).

Creating an entry with:

const value = {
  name: 'test name',
  service: {
    domain: 'test domain'
  }
}

knex('card').insert(value).returning('*');

Inserts the row:

id name service
1 test {“domain”:”test domain”}

Then updating with:

const updateValue = {
  name: 'test name',
  service: {
    domain: 'updated domain'
  }
}

knex('card').where('id', 1).update(updateValue).returning('*');
  

Updates the row to:

id name service
1 test [object Object]

Is this the intended behavior? I need the service column to remain a stringified version of the JSON so that I can parse it on the frontend.

I set it up with a very stripped-down version so I can clearly see exactly what is being sent to the database. I can see that the format of the incoming object is identical for creating and updating the entry, so I’m not sure why it’s not updating correctly.

How can I monitor a users web activity using some form of JS (with consent of course) [closed]

I am trying to create a web app that monitors a persons activity on the internet,in this case te web and anylzes that data to give the user a report on their personality. I have tried learning about cookies and everything however you have to use thrid party sources. I want to do this with the users consent because it is unethical to do these actions without a users consent.

How would I go about approaching this problem?? I have searched google but all I can find is things about cookies and activity on the singular webpage the user is using. I know it may seem like a breach of privacy so that is why I am not getting the results I would like to get. However with consent is this even possible to do??

Sveltekit: display alert message after redirecting

I’m working on a project using Sveltekit for the frontend. To display on screen alert messages I had created the following.

In +layout.svelte (the main layout file) I have:

<!-- Main content -->
            <main class="items-center min-h-screen justify-center w-full pt-12 p-12 border-accent-content/5 bg-gray-100">
                <Alert />
                <slot/>
            </main>

Notice the <Alert /> component.

The <Alert /> component looks like:

<script>

    import { ALERT_TYPE, alertMessage, alertType } from "../stores/alert.js";
    import { fade } from 'svelte/transition';

    // computed property to display the pertinent icon depending on the type of alert.
    $: alertIcon = () => {
        switch ($alertType) {
            case ALERT_TYPE.SUCCESS:
                return `<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current flex-shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24" style="display: inline" ><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"  /></svg>`
            case ALERT_TYPE.ERROR:
                return `<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current flex-shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24" style="display: inline"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>`
            case ALERT_TYPE.WARNING:
                return `<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current flex-shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24" style="display: inline"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>`
            case ALERT_TYPE.INFO:
            default:
                return `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current flex-shrink-0 w-6 h-6" style="display: inline"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>`
        }
    }

</script>

<!-- Display the alert only if there's a message to be displayed -->
{#if ($alertMessage) }
    <div class="alert alert-{$alertType} shadow-lg mb-8" transition:fade>
        <div>
            { @html alertIcon() }
            <span>{ @html $alertMessage }</span>
        </div>
    </div>
{/if}

And I’ve created a store so I can access whatever value is stored in the store from my layout file:

import { writable } from "svelte/store";

export const ALERT_TYPE = {
    ERROR: 'error',
    INFO: 'info',
    SUCCESS: 'success',
    WARNING: 'warning',
};

Object.freeze(ALERT_TYPE);

export const alertMessage = writable('');
export const alertType = writable('');

/**
 * Displays a new alert message by setting up the alert values in the store.
 * @param message
 * @param type
 * @param resetTimeInSecs
 */
export const displayAlert = (message, type = ALERT_TYPE.INFO, resetTimeInSecs=5) => {
    alertMessage.set(message);
    alertType.set(type);

    if (resetTimeInSecs) {
        setTimeout(() => {
            alertMessage.set("");
        }, resetTimeInSecs * 1000);
    }
}

This works just fine when I’m displaying the message and stay in the same page where it was triggered, but it works a bit funky when I redirect to another page.

Let’s say I have a page such as the following:

<script>
    import CategoryForm from "$lib/forms/CategoryForm.svelte";
    import {ALERT_TYPE, displayAlert} from "../../../lib/stores/alert.js";
    import {browser} from "$app/environment";

    /* data returned from load function in +page.server.js */
    export let data;

    /* data returned from actions function in +page.server.js */
    export let form;

    if (data.errors) {
        if (browser) { // to prevent error window is not defined, because it's SSR
            displayAlert(data.errors, ALERT_TYPE.ERROR, 10);
            window.location.href = '/categories';
        }
    }

</script>

<CategoryForm formData={ {...data, ...form}} loadedData={data} mode="edit" />

In this page, whenever errors are returned from the server in data I want to redirect to /categories and show the error alert message. It works as it is now, but I see the message in the current form before I’m redirected and that simply looks ugly. I want the message to be visible only in /categories.

Is there a better way to do this? I’ve got two possible solutions but none of them seem very elegant nor the right way to do it for me, so I’m looking for other suggestions.

1 Use setTimeout. That way I can give some time for the redirect to happen.
2 Use an extra parameter in displayAlert. This parameter would be optional and would indicate the page where the alert is allowed to be displayed. In this specific case that parameter would be /categories. I can take the url object and get the current location, if the location matches that of the one passed in the param then go ahead and show the alert.

Any suggestions?

How can I create a carousel that moves down slowly using JavaScript?

I’m working on a web project and I’d like to implement a carousel that behaves a bit differently from the typical left-to-right or right-to-left carousels. Instead, I want the carousel to move down the page slowly, displaying one item at a time. Think of it as a vertical-scrolling carousel.

const [activeSlide, setActiveSlide] = useState(0); // State for Carousel 

useEffect(() => {
  const interval = setInterval(() => {
    setActiveSlide((prevSlide) => (prevSlide + 1) % slides.length);
  }, 3000);

  return () => {
    clearInterval(interval);
  };
}, [])
  • The carousel should display one item at a time and smoothly scroll down to the next item after a certain interval (e.g., every 3 seconds).
  • Should move automatically
  • The carousel should loop back to the first item when it reaches the end.
    I’m not sure where to start with this. Are there any JavaScript libraries or techniques that can help me achieve this effect? Any guidance or code examples would be greatly appreciated!

How to remove closed websockets from browser developer tools?

I’m creating websocket connection code using JavaScript.
My code recreates the websocket connection when it is closed.

My Websocket Connection Code :

const init = () => {
    socket = new WebSocket(`${DEFINES.APP_URL.CHATTING}`);

    socket.onopen = (message: Event) => {
      login({ userId: agentInfo.id, tenantId: agentInfo.tenantId });
    };

    socket.onclose = (message: CloseEvent) => {
      setTimeout(() => {
        init();
      }, 1000 * 10);
    };
  };

When a socket is closed, a reconnection attempt is made, but web sockets with closed connections remain in the browser developer tools.

How can I remove closed websocket to browser develover tool?
Is there a way to remove it from developer tools when the connection is lost without refreshing?
When network conditions are poor, excessive closed sockets accumulate in the developer tools, causing lag.

How do i sort an array so that it loops from the center in a circle like a snake? [closed]

I was wondering how you can sort an array so that it spirals from the center in a circle like a snake

For example:

[0,1,2,3,4,5,6,7,8] -> [8,1,2,7,0,3,6, 5, 4]

[0,1,2,3,4,5,6,7,8,9] -> [9,null, null,8,1,2,7,0,3,6, 5, 4]

[0,1,2,3,4,5,6,7,8,9, 10, 11, 12] -> [9,10,11, 12,8,1,2, null,7,0,3, null6, 5, 4, null]`

Ideally in javascript would be good but any language is fine

Change in div content not update in DOM

I´m trying to make a chrome extension what working in whatsapp web, but something very strange is happening. When trying to change a div content who has a P and SPAN tags, exactly the place of text to change, is happening what does not update the DOM on the screen, even though the command runs without error. Noting that I already tried with innerHTML, innerText and textContent properties. It even worked in tests in the W3schools try, where the text change appears. What can it be?

`document.addEventListener('keyup', 
    function(event) {
        const clickedElem = event.target
        console.log(clickedElem.tagName);

        if (clickedElem.contentEditable === "true") {
            console.log('is here');
            console.log(clickedElem.innerText);
            let x = clickedElem.innerText;
            if (x === 'xxx') {
                console.log('match');
                $(clickedElem).find('span').innerText='New text';
                console.log(clickedElem.innerText);

            }
        }
    })`

`

enter image description here

i have card on click iwant her id to displayed on the link and her content displayed also

I am learning React and I want to develop a trading website. When I click on any product, I want it to take me to its page without designing a page for each product. I want one page, and when I click on any product, the design is applied to the data of that product. I want you, if possible, to have a complete example of how to fetch the data from the object.

I am learning React and I want to develop a trading website. When I click on any product, I want it to take me to its page without designing a page for each product. I want one page, and when I click on any product, the design is applied to the data of that product. I want you, if possible, to have a complete example of how to fetch the data from the object.

i didn’t find any resources to try

Div Squishes when Moved

I’m messing around with html/js/css to make a web app that tells you how to load a barbell with plates for powerlifting/weightlifting.

I’m using js to create a div for each plate that is required to be loaded, as well as an additional div which represents a ‘collar’. When I create a low amount of divs it represents correctly as follows:
normal

When I create too many divs it begins to ‘squish’ the additional ‘collar’ div, as well as the ‘plate’ divs as such:
squished
very squished

Here is the hierarchy of divs in their parent div they’re appended to on creation:
hierarchy of divs

The css for the collar divs are here:

.barbell_collar_left {
background: rgb(133,133,133);
background: linear-gradient(0deg, rgba(133,133,133,1) 0%, rgba(208,208,208,1) 33%, rgba(247,247,247,1) 66%, rgba(202,202,202,1) 100%);
bottom: calc(var(--barbell_shoulder_height)/var(--scale_factor)/-2 + var(--barbell_collar_height)/var(--scale_factor)/2);
height: calc(var(--barbell_collar_height)/var(--scale_factor));
position: relative;
right: calc(var(--barbell_collar_width)/var(--scale_factor));
width: calc(var(--barbell_collar_width)/var(--scale_factor));
display: flex;
flex-direction: row-reverse;
}

.collar_left {
background: rgb(133,133,133);
background: linear-gradient(0deg, rgba(133,133,133,1) 0%, rgba(208,208,208,1) 33%, rgba(247,247,247,1) 66%, rgba(202,202,202,1) 100%);
bottom: calc(var(--barbell_collar_height)/var(--scale_factor)/2);
clip-path: polygon(25% 0, 85% 0, 100% 15%, 100% 85%, 85% 100%, 25% 100%, 0 85%, 0 15%);
height: calc(var(--collar_height)/var(--scale_factor));
position: relative;
right: 0px;
width: calc(var(--collar_width)/var(--scale_factor));
}
.collar_end_left {
background: rgb(133,133,133);
background: linear-gradient(0deg, rgba(133,133,133,1) 0%, rgba(208,208,208,1) 33%, rgba(247,247,247,1) 66%, rgba(202,202,202,1) 100%);
bottom: calc(var(--collar_end_height)/var(--scale_factor)/3.5);
clip-path: polygon(75% 0, 90% 5%, 85% 15%, 85% 85%, 90% 95%, 75% 100%, 60% 85%, 60% 15%);
height: calc(var(--collar_end_height)/var(--scale_factor));
right: -5px;
position: relative;
width: calc(var(--collar_width)/var(--scale_factor));
}
.collar_shaft_left {
background: rgb(133,133,133);
background: linear-gradient(0deg, rgba(133,133,133,1) 0%, rgba(208,208,208,1) 33%, rgba(247,247,247,1) 66%, rgba(202,202,202,1) 100%);
bottom: 50px;
clip-path: polygon(0 80%, 0 60%, 100% 60%, 100% 100%, 80% 100%, 80% 80%);
height: 40px;
right: -55px;
position: relative;
width: 40px;
}
.collar_handle_left {
background: radial-gradient(circle at 25% 15%, white 1px, grey 3%, rgb(26, 26, 26) 60%, grey 100%);  
bottom: 32px;
clip-path: circle(50% at 50% 50%);
height: 20px;
right: -57px;
position: relative;
width: 20px;
}

Am I missing something simple here, perhaps it has something to do with the position type? Fairly new to html/js/css so just tinkering and learning along the way!

Thanks for reading

I’ve tried changing the position types but I’m too inexperienced to even figure out what it’s trying to do and how to approach it.

When I create the divs without the additional ‘collar’ div, I don’t have this issue until the ‘plate’ divs reach the end of their parent ‘barbell_collar_left’ div?

How to write Angular Unit test case for functional guard that gets value from ngrx store

I have the following function for guard:

export const authGuardGuard: CanActivateFn = () => {
  const store = inject(Store);

  return store.pipe(select(selectUserRegistration)).pipe(
    map((result) => {
      if (!result.success) {
        store.dispatch(UserActions.navigateToRegistration());
      }

      return result.success;
    })
  );
};

And Unit test case:

describe('authGuardGuard', () => {
  const executeGuard: CanActivateFn = (...guardParameters) =>
    TestBed.runInInjectionContext(() => authGuardGuard(...guardParameters));

  let mockStore: MockStore<UserState>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [StoreModule.forRoot()],
      providers: [
        provideMockStore({
          initialState: {
            user: undefined,
            registration: {
              success: true,
              error: false,
            },
          },
        }),
      ],
    });

    mockStore = TestBed.inject(MockStore);
  });

  it('should be created', () => {
    expect(executeGuard).toBeTruthy();
  });

  it('should return true if registration is successful', async () => {
    const route: ActivatedRouteSnapshot = {} as any;
    const state: RouterStateSnapshot = {} as any;

    mockStore.dispatch(UserActions.userRegistrationSuccess({ success: true }));

    const guard = executeGuard(route, state);
    expect(guard).toBeTrue();
  });
});

The executeGuard(route, state) returns store function not a boolean value like:

Store{actionsObserver: ActionsSubject{closed: false, currentObservers: []...

What am I doing wrong? Is there a better way to test functional guard?

Why won’t or statement work in a for loop? [closed]

I was looking at the w3schools JavaScript tutorial and found something that made it crash. I was trying to replace the break statement with the same thing in the second statement of the for loop. This isn’t really a problem, I just think there’s something I’m not understanding.

This was the code they had:

<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

And it works perfectly fine. Then I changed it to this:

<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10 || i !== 3; i++) {
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Then, if I run it, the webpage crashes.
if I change the or(||) to an and(&&), then it works.
Why is this?

How to access an array within an object within an array in JavaScript? [duplicate]

First I have to say I’ve been trying to solve this doubt I have by looking at other similar questions already with solutions . But I couldn’t find exactly what would solve my problem. Maybe I’m asking the wrong question… I’m here to find out.

Let’s say I have an array with objects, and each object has a property with more than one value:

const movies = [

{
  name: "movie1",
  keywords: ["black-and-white", "independent"],
  points: 0
};

{
  name: "movie2",
  keywords: ["black-and-white", "independent"],
  points: 0
};

{
  name: "movie3",
  keywords: ["color", "studio production"],
  points: 0
};

{
  name: "movie4",
  keywords: ["superhero", "blockbuster"],
  points: 0
}

];

First question: is “keywords” an array itself or just a property with more than one value inside the objects of the array “movies“?

And then the big question: how can I access it?

For example, I’m creating a quiz with questions about movies and I want that when someone clicks a button confirming that they enjoy black-and-white movies, then all the movies in the array that have the keyword “black-and-white” would get 1 point. How would you do that?

I came up with a code that almost solves this problem:

function addPoints(keyWord) {
for (i = 0; i < movies.length; i++) {
if (movies[i].keywords == keyWord) {
movies[i].points++}
else {
  movies[i].points--
}
}
};

document.getElementById("questionOneYes").addEventListener("click", function () {
  addPoints("black-and-white")
});

The code above works perfectly if the property keywords has only one value. But it doesn’t work if it has more than one, like I intend it to be.

I tried to treat the keywords property like an array and to access it through the includes() method:

function addPoints(keyWord) {
for (i = 0; i < movies.length; i++) {
if (movies[i].keywords.includes(keyWord)) {
movies[i].points++}
else {
  movies[i].points--
}
}
};

It didn’t work. I got this error message:
“Uncaught TypeError: Cannot read properties of undefined (reading ‘includes’)”

So, please help. There must be a way to make this work, otherwise I’ll have to create many properties in every object, each with a different keyword, and then more than one function to access each of these different keyword properties… and that sounds like too many lines of code for something that should be simpler and more concise to make.

Is there a way to reorder an array by comparing 2 different values and create a new one indicating previousSibling in a new array?

Given the following array

[
    {
        "id": "4d7ceda1-2058-479d-b499-8e56913c67e9",
        "title": "text 01"
    },
    {
        "id": "c0dabc89-1bf0-4f35-a17b-19adf0126f21",
        "title": "text 02",
        "previousSibling": "cfff0c5f-4339-4767-afce-a0b1526d53cb"
    },
    {
        "id": "cfff0c5f-4339-4767-afce-a0b1526d53cb",
        "title": "text 03",
        "previousSibling": "87584074-3166-42e2-8346-29210b834117"
    },
    {
        "id": "ed9e0ef4-a07b-4483-b5f0-9c5f0d08e0be",
        "title": "text 04",
        "previousSibling": "c0dabc89-1bf0-4f35-a17b-19adf0126f21"
    }
]

I need to reorder based on 2 attributes id and previousSibling.
This first array comes from the API, and I need to reorder it using previousSibling as a reference for the list. So, if the id has the value 02, the next item of the array that has the attribute previousSibling should have the value 02 and so forth.

So, it should look sort of like this one below

[
    {
        "id": "4d7ceda1-2058-479d-b499-8e56913c67e9",
        "title": "text 01"
    },
    {
        "id": "c0dabc89-1bf0-4f35-a17b-19adf0126f21",
        "title": "text 02",
        "previousSibling": "4d7ceda1-2058-479d-b499-8e56913c67e9"
    },
    {
        "id": "cfff0c5f-4339-4767-afce-a0b1526d53cb",
        "title": "text 03",
        "previousSibling": "c0dabc89-1bf0-4f35-a17b-19adf0126f21"
    },
    {
        "id": "ed9e0ef4-a07b-4483-b5f0-9c5f0d08e0be",
        "title": "text 04",
        "previousSibling": "cfff0c5f-4339-4767-afce-a0b1526d53cb"
    }
]

I have tried to compare like current.previousSibling === arrayPrevItem[i - 1].id within a filter but no success.
Any idea will be appreciated! Thank you in advance!

How to change a pie color already rederized with Chart.js?

i’m trying to change the color of a slice of pie chart that’s already renderized.

I have a viable with all the info, Data, label, color, percent and everything.

now i want to make a input or whatever to change the slice color in chart.js

This is my raw code

<body>
  <div style="display: inline-block;" class="areagraph"></div>//just filled by js with the elements  
</body>
<script>
    const allCharts = [
        { 
            name: "Gender",
            type: "pie",
            data: [
                { label: "Homem Trans", backgroundColor: "#213C64", data: 434, total: 2000, percentage:14.5 }
                  `Other Genders`
            ]
       
    ];

    allCharts.forEach(chart => {
    const containerchart = document.createElement('div');
    containerchart.classList.add('containerchart');

    const dataContainer = document.createElement('div');
    dataContainer.classList.add('data-table');

    const title = document.createElement('h1');
    title.textContent = chart.name + " in " + chart.type;

    const canvascontainerchart = document.createElement('div');
    canvascontainerchart.classList.add('graphContainer');

    const canvas = document.createElement('canvas');
    canvas.id = 'pie-chart-' + chart.name.toLowerCase().replace(/s/g, '-');
    canvascontainerchart.appendChild(canvas);

    const table = document.createElement('table');
    table.classList.add('table', 'table-bordered', 'table-hover');
    const thead = document.createElement('thead');
    const tbody = document.createElement('tbody');

    const theadRow = document.createElement('tr');
    const thColor = document.createElement('th');
    thColor.textContent = 'Cor'; // Nome da coluna de cor
    const thName = document.createElement('th');
    thName.textContent = chart.name;
    const thNumber = document.createElement('th');
    thNumber.textContent = 'Number';
    const thPercentage = document.createElement('th');
    thPercentage.textContent = 'Percentage';
    theadRow.appendChild(thColor);
    theadRow.appendChild(thName);
    theadRow.appendChild(thNumber);
    theadRow.appendChild(thPercentage);
    thead.appendChild(theadRow);

    chart.data.forEach(item => {
      const tbodyRow = document.createElement('tr');
      const tdColor = document.createElement('td');
      const colorDiv = document.createElement('div');
      colorDiv.style.width = '20px'; // Largura da div redonda
      colorDiv.style.height = '20px'; // Altura da div redonda
      colorDiv.style.borderRadius = '50%'; // Forma redonda
      colorDiv.style.backgroundColor = item.backgroundColor; // Cor de fundo correspondente
      tdColor.appendChild(colorDiv);
      
      const tdName = document.createElement('td');
      tdName.textContent = item.label;
      const tdNumber = document.createElement('td');
      tdNumber.textContent = item.data;
      const tdPercentage = document.createElement('td');
      const percentage = item.percentage;
      tdPercentage.textContent = percentage + '%';
      tbodyRow.appendChild(tdColor);
      tbodyRow.appendChild(tdName);
      tbodyRow.appendChild(tdNumber);
      tbodyRow.appendChild(tdPercentage);
      tbody.appendChild(tbodyRow);
    });

    table.appendChild(thead);
    table.appendChild(tbody);


    dataContainer.appendChild(table);
    
    /* Graph */
    containerchart.appendChild(canvascontainerchart);

    /* Table */
    containerchart.appendChild(dataContainer);

    const areagraphDiv = document.querySelector('.areagraph');

    areagraphDiv.appendChild(containerchart);

    // document.body.appendChild(containerchart);      
      
      new Chart(canvas, {
              type: chart.type,
              data: {
                labels: chart.data.map(item => item.label),
                datasets: [{
                  backgroundColor: chart.data.map(item => item.backgroundColor),
                  data: chart.data.map(item => item.percentage), // Use the raw percentage values
                }],
              },
              options: {
                plugins: {
                  title: {
                    text: chart.name,
                    display: true,
                    fullSize: true,
                    font: {
                      size: 30,
                    },
                  },
                  tooltip: {
                    callbacks: {
                      label: (percentage) => {
                        return percentage.value + "%"; // Append "%" to the tooltip label
                      },
                    },
                  },
                },
                responsive: true,
              },
    });

</script>

Well, this show how im doing the job. pick color from propety backgroundColor.