Two jquery pie charts same page

I have two adjustable jquery pie charts on the same page. I added PieID2 to create the second chart, but the first chart isn’t completing the 360 degree circle now. Can anyone assist? I’m not sure what I need to change or add to get multiple pie charts on the same page and have all charts functioning properly.

https://codepen.io/Goatsy/pen/abYJQzE

<section>
    <div class="pieID pie">
      
    </div>
    <ul class="pieID legend">
      <li>
        <em>Unsheltered</em>
        <span>514</span>
      </li>
      <li>
        <em>Sheltered</em>
        <span>410</span>
      </li>
    </ul>
  </section>

<section>
    <div class="pieID2 pie">
      
    </div>
    <ul class="pieID2 legend">
      <li>
        <em>Adults (25-60)</em>
        <span>304</span>
      </li>
      <li>
        <em>Youth (18-24)</em>
        <span>87</span>
      </li>
      <li>
        <em>Seniors</em>
        <span>35</span>
      </li>
      <li>
        <em>Children</em>
        <span>4</span>
      </li>
      <li>
        <em>Unknown</em>
        <span>81</span>
      </li>
    </ul>
</section>

JS:

function sliceSize(dataNum, dataTotal) {
  return (dataNum / dataTotal) * 360;
}
function addSlice(sliceSize, pieElement, offset, sliceID, color) {
  $(pieElement).append("<div class='slice "+sliceID+"'><span></span></div>");
  var offset = offset - 1;
  var sizeRotation = -179 + sliceSize;
  $("."+sliceID).css({
    "transform": "rotate("+offset+"deg) translate3d(0,0,0)"
  });
  $("."+sliceID+" span").css({
    "transform"       : "rotate("+sizeRotation+"deg) translate3d(0,0,0)",
    "background-color": color
  });
}
function iterateSlices(sliceSize, pieElement, offset, dataCount, sliceCount, color) {
  var sliceID = "s"+dataCount+"-"+sliceCount;
  var maxSize = 179;
  if(sliceSize<=maxSize) {
    addSlice(sliceSize, pieElement, offset, sliceID, color);
  } else {
    addSlice(maxSize, pieElement, offset, sliceID, color);
    iterateSlices(sliceSize-maxSize, pieElement, offset+maxSize, dataCount, sliceCount+1, color);
  }
}
function createPie(dataElement, pieElement) {
  var listData = [];
  $(dataElement+" span").each(function() {
    listData.push(Number($(this).html()));
  });
  var listTotal = 0;
  for(var i=0; i<listData.length; i++) {
    listTotal += listData[i];
  }
  var offset = 0;
  var color = [
    "#182a54", 
    "#025971", 
    "#ecaa20", 
    "#5a622b", 
    "#82332e", 
    "purple", 
    "turquoise", 
    "forestgreen", 
    "navy", 
    "gray"
  ];
  for(var i=0; i<listData.length; i++) {
    var size = sliceSize(listData[i], listTotal);
    iterateSlices(size, pieElement, offset, i, 0, color[i]);
    $(dataElement+" li:nth-child("+(i+1)+")").css("border-color", color[i]);
    offset += size;
  }
}
createPie(".pieID.legend", ".pieID.pie");
createPie(".pieID2.legend", ".pieID2.pie");

Change height and width of a React Player thumbnail using light prop

I set the thumbnail of the React Player using the light prop. Example code is as follows.

 <ReactPlayer                                              
       url= 'https://samplevideo.com'
       light = 'https://sampleimage.com'
       playing
       controls/>

This works as expected. But the thumbnail image does not always fit the react player. Sometimes only a part of the actual image is shown as the thumbnail. Is there a way to change the height and width of the thumbnail image of the react player?

Why is event listener “resize” slower than css @media screen?

I’m showing and hiding different headings depending on the device screen width. As react allows me to mount and unmount a component depending on a state I sometimes used the event listener addEventLister("resize", handleResize) to show and hide elements.
But with this method on a new page refresh, some flickering appeared as the default value of state was replaced by the actual evaluated value of the screen width, which caused the bigger typo to be shown for a millisecond before it was hidden again.
I discovered this won’t happen with @media screen and display: none.
Why is it so slow? And is there any workaround for cases where I can’t solve it in CSS, so a way to prioritize the event listener to evaluate before showing the wrong heading?
What’s the go-to way for these scenarios, as this must be a basic issue on all responsive sites?

Example for a custom hook to listen for window changes:

  const [screenSize, setScreenSize] = useState<Size>({
    width: 0,
    height: 0,
  });

  useEffect(() => {
    const handleResize = () => {
      setScreenSize({ width: window.innerWidth, height: window.innerHeight });
    };
    addEventListener("resize", handleResize);

    handleResize();
    return () => removeEventListener("resize", handleResize);
  }, []);

Css example to do the same:

.title {
  display: flex;
}
@media screen and (max-width: 768px) {
  .title {
    display: none;
  }
}

Complex question : how to filter every word I want with filter, includes and dataset?

I’m quite a beginner in Javascript and I’m french. I have a project and it’s goal is to filter by tags some cooking recipes (french words but don’t worry). So my aim is to click on an ingredient (like “Sugar” or “Sucre”), and it’s suppose to filter every recipe from an array that includes this ingredient by creating a tag.

Here’s my function to create a tag :

export function createIngTag(label, dataProperty, id) {
  const div = document.createElement("div")
  div.setAttribute("class", "tag")
  div.classList.add("ing-tag")
  div.setAttribute("data-property", dataProperty)
  div.setAttribute("id", id)
  const span = document.createElement("span")
  span.setAttribute("class", "tag-span")
  span.innerHTML = label
  const closeBtn = document.createElement("i")
  closeBtn.classList.add("far")
  closeBtn.classList.add("fa-times-circle")
  closeBtn.classList.add("close-button")
  closeBtn.setAttribute("data-item", label)
  closeBtn.addEventListener("click", closeTag)

  function closeTag(e) {

    const value = e.target.getAttribute("data-item")
    const index = tagsArray.findIndex((div) => div.getAttribute("data-property").toLowerCase() === value.toLowerCase());
    console.log(index)
    if (index === -1) {
      return alert("NOT FOUND")
    }
    tagsArray.splice(index, 1)
    console.log(tagsArray)
    selectedRecipesArray.prop = [...recipes]
    tagsArray.forEach((tag) => {

      selectedRecipesArray.prop = filterByTags(selectedRecipesArray, tag);
      console.log(selectedRecipesArray.prop)
    });
    closeBtn.parentElement.remove()
    changeRecipesSection()

    displayRecipes(selectedRecipesArray)
  }

  tagsSpace.appendChild(div)
  div.appendChild(span)
  div.appendChild(closeBtn)
  tagsArray.push(div)
  console.log(tagsArray)

  return div
}

And here is my listener for each ingredient you click on, which is also part of my ingredient list factory :

div.addEventListener("click", () => {
  if (!document.getElementById(span.textContent)) {
    createIngTag(span.textContent, span.textContent, span.textContent)
    tagsArray.forEach((tag) => {
      selectedRecipesArray.prop = [...recipes]
      selectedRecipesArray.prop = filterByTags(selectedRecipesArray, tag);
      console.log(selectedRecipesArray.prop)
    });

    changeRecipesSection()
    console.log(selectedRecipesArray.prop)
    displayRecipes(selectedRecipesArray.prop)
  }
})

At last, here is my function filterByTags that allows, once the tag is created to set a list of recipes supposed to match with the tag created :

export function filterByTags(recipesArr, tag) {
  const result = recipesArr.filter((object) => object.ingredients.some((ingObj) =>
    ingObj.ingredient.toLowerCase().includes(tag.dataset.property.toLowerCase())
  ));

  return result;
}

Here is the problem : the filter works very well with some ingredients like Sugar, Flour, Eggs, Butter (in french : Sucre, Farine, Oeufs, Beurre) but it doesn’t work with most of the ingredients from the list, the returned Array is empty. Can you help me with that ?

Here’s the link to my repo : https://github.com/Romain-6793/RomainClaudot_7_30052022

thanks in advance.

How to change the color/size/etc of dynamically created buttons in javascript?

I have created dynamic buttons in vuejs where each button represents a different answer to a question.
My goal is: when I get the answer wrong, the correct option is highlighted in green.
Is it also possible to change other settings of these “BaseButtons” with CSS? How can I do this?

<template>
  <div class="container-botoes">
     <BaseButton class="optionsButtons" 
     v-for="options in optionsAnswers" 
     :key="options.id" @click="handleAnswer(options)">
       {{options.ans}}
     </BaseButton>
  </div>
</template>
methods:{
  handleAnswer(options){
    if (options.id === this.correctAnswer){
      this.playerHit = true;
    }
    else {
      this.opponentHit = true;
      
    }
    this.nextquestion();
  },

count forEach loop in JavaScript

I am trying to find the total number of a specific character is in string.

for example

myString = " this is my string ";

I want to count how many “s” is in myString. I tried the following:

function myFunction(a, b) {
  const letters = b.split("");
  console.log(letters);
 
  letters.forEach(letter => {
    let letterCount = 0;
    if(letter === a) {
      console.log("yes")
      letterCount++;       
    }
    console.log(letterCount);      
  })
}

myFunction('s', 'this is my string') // Expected result: 3

Is there a faster way to loop through nested array of objects than nested for loops?

I’ve been learning the fundamentals of Big(o) and after looking at some old code I’ve written, I habitually use nested for loops for problems like this instead of implementing a better approach with a faster run time. For instance:

const webhooks = [
  [
    {
      topic: "CUSTOMERS_CREATE",
      path: `${process.env.HOST}/webhooks/customers/create`,
    },
    {
      topic: "CUSTOMERS_UPDATE",
      path: `${process.env.HOST}/webhooks/customers/update`,
    },
    {
      topic: "CUSTOMERS_DELETE",
      path: `${process.env.HOST}/webhooks/customers/delete`,
    },
  ],
  [
    {
      topic: "CHECKOUTS_CREATE",
      path: `${process.env.HOST}/webhooks/checkouts/create`,
    },
    {
      topic: "CHECKOUTS_UPDATE",
      path: `${process.env.HOST}/webhooks/checkouts/update`,
    },
  ],
  [
    {
      topic: "ORDERS_CREATE",
      path: `${process.env.HOST}/webhooks/orders/create`,
    },
    {
      topic: "ORDERS_UPDATED",
      path: `${process.env.HOST}/webhooks/orders/update`,
    },
    {
      topic: "ORDERS_DELETE",
      path: `${process.env.HOST}/webhooks/orders/delete`,
    },
  ],
  [
    {
      topic: "PRODUCTS_CREATE",
      path: `${process.env.HOST}/webhooks/products/create`,
    },
    {
      topic: "PRODUCTS_UPDATE",
      path: `${process.env.HOST}/webhooks/products/update`,
    },
    {
      topic: "PRODUCTS_DELETE",
      path: `${process.env.HOST}/webhooks/products/delete`,
    },
  ],
];

 // Registering the webhooks
 webhooks.forEach(async (elm) => {
  elm.forEach(async (el) => {
    Shopify.Webhooks.Registry.addHandler(el.topic, {
      path: el.path,
      webhookHandler: webhookController,
    });
  });
});

In this snippet, I am looping over the initial array, then the nested array to finally get the topic and path for each element. Then I make a function call with those properties for further processing. While a nested for loop works, I know it will have a runtime of O(n^2) which is awful at scale. I thought about converting this array of objects into a map, but are there caveats to this approach I’m missing? If so, what alternative methods could I use to achieve a much more ideal runtime like O(log(n))?

eslint Plugin “react” was conflicted between “package.json » eslint-config-react-app »

Failed to compile.

[eslint] Plugin “react” was conflicted between “package.json » eslint-config-react-app » C:UsersUserDownloadssocial-media-app-mainsocial-media-app-mainsrcpageshomereelsnode_moduleseslint-config-react-appbase.js” and “BaseConfig » C:UsersUserDownloadssocial-media-app-mainsocial-media-app-mainsrcpagesHomereelsnode_moduleseslint-config-react-appbase.js”.
ERROR in [eslint] Plugin “react” was conflicted between “package.json » eslint-config-react-app » C:UsersUserDownloadssocial-media-app-mainsocial-media-app-mainsrcpageshomereelsnode_moduleseslint-config-react-appbase.js” and “BaseConfig » C:UsersUserDownloadssocial-media-app-mainsocial-media-app-mainsrcpagesHomereelsnode_moduleseslint-config-react-appbase.js”.

webpack compiled with 1 error

How to fix this i have tried npm update remove eslint-config-react-app and add eslint-config-react-app@6 but it didn’t workimage1
image2

Find something in an very long array

I have a problem in JavaScript.
I have an array which looks like this:

[MemberData], [MemberData], [MemberData], [MemberData], …(Goes up to 200)
Inside the [MemberData] there is an UUID with a value. I wanna compare a variable to all of these UUIDs to check if an UUID is the same as the variable.

Cna someone help me doing this? I would really appreaciate it.
Thanks!

Deserializing a key of type number in KafkaJS

I’m trying to decode a topic key of a type number with KafkaJS.
The key object arrives as a Buffer, but I’m struggling with finding a way to decode it’s value.
Example:

// message.key equals to Buffer.from([0x49, 0x57, 0x48, 0x55, 0x52, 057, 0x52])

const decodedKey = decodeBuffer(message.key);
// Should be equal to 1907494

I assume that it’s a product of Java serialization.
‘How can I deserialize it in JavaScript?

Javascript problem or more lack of knowledge than anything

Hopefully this is fairly simple.

This is my current code below. It is generating a random number for me on loading the page and works fine for the target div. However, I want this to run this function within 8 separate divs. I obviously cannot have 8 divs with the same id so I changed this to getElementByClassName and changed the class on my div to vvv and got rid of the id but for some reason this doesn’t work?

Also, do I need anything else in my script to call this function for more than one div? Any help much appreciated!

<script>
        let text = "VAC";       
        
        window.onload = function ()
        {
        var output = document.getElementById("vvv");
        
        setInterval(function ()
        {
            output.innerHTML = Math.floor(Math.random() * (115 - 105 + 1)) + 105 + " " + text; 
        }, 2000);//this value is the time between generating the number//
        };
</script>

How to remove the status row in data grid table?

Goal:
Not displaying the status row in the bottom.

Problem:
How do you do it?

enter image description here

CodeSandbox:
https://codesandbox.io/s/69384072-how-to-delete-multiple-rows-with-select-checkboxes-from-material-ui-data-grid-re-forked-p75sku?file=/demo.tsx

Thank you!


import * as React from "react";
import IconButton from "@mui/material/IconButton";
import { DataGrid, GridRowsProp, GridColDef } from "@mui/x-data-grid";
import DeleteIcon from "@mui/icons-material/Delete";

const _rows: GridRowsProp = [
  { id: 1, col1: "Hello", col2: "World" },
  { id: 2, col1: "XGrid", col2: "is Awesome" },
  { id: 3, col1: "Material-UI", col2: "is Amazing" },
  { id: 4, col1: "Hello", col2: "World" },
  { id: 5, col1: "XGrid", col2: "is Awesome" },
  { id: 6, col1: "Material-UI", col2: "is Amazing" },
  { id: 7, col1: "Material-UI", col2: "is Amazing" },
  { id: 8, col1: "Hello", col2: "World" },
  { id: 9, col1: "XGrid", col2: "is Awesome" },
  { id: 10, col1: "Material-UI", col2: "is Amazing" },
  { id: 11, col1: "Hello", col2: "World" },
  { id: 12, col1: "XGrid", col2: "is Awesome" },
  { id: 13, col1: "Material-UI", col2: "is Amazing" },
  { id: 14, col1: "Hello", col2: "World" },
  { id: 15, col1: "XGrid", col2: "is Awesome" },
  { id: 16, col1: "Material-UI", col2: "is Amazing" },
  { id: 17, col1: "Material-UI", col2: "is Amazing" },
  { id: 18, col1: "Hello", col2: "World" },
  { id: 19, col1: "XGrid", col2: "is Awesome" },
  { id: 20, col1: "Material-UI", col2: "is Amazing" },
  { id: 21, col1: "Hello", col2: "World" },
  { id: 22, col1: "XGrid", col2: "is Awesome" },
  { id: 23, col1: "Material-UI", col2: "is Amazing" },
  { id: 24, col1: "Hello", col2: "World" },
  { id: 25, col1: "XGrid", col2: "is Awesome" },
  { id: 26, col1: "Material-UIII", col2: "is Amazinggggg" }
];

export default function ControlledSelectionGrid() {
  const [rows, setRows] = React.useState(_rows);
  const [selectionModel, setSelectionModel] = React.useState([]);
  const columns: GridColDef[] = [
    { field: "col1", headerName: "Column 1", width: 150 },
    { field: "col2", headerName: "Column 2", width: 150 },
    {
      field: "delete",
      width: 75,
      sortable: false,
      disableColumnMenu: true,
      renderHeader: () => {
        return (
          <IconButton
            onClick={() => {
              const selectedIDs = new Set(selectionModel);
              // you can call an API to delete the selected IDs
              // and get the latest results after the deletion
              // then call setRows() to update the data locally here
              setRows((r) => r.filter((x) => !selectedIDs.has(x.id)));
            }}
          >
            <DeleteIcon />
          </IconButton>
        );
      }
    }
  ];

  return (
    <div style={{ width: "100%" }}>
      <DataGrid
        autoHeight
        rows={rows}
        columns={columns}
        checkboxSelection
        onSelectionModelChange={(ids) => {
          setSelectionModel(ids);
        }}
      />
    </div>
  );
}

React dnd how to scroll hovering over container?

  const [dropProps, drop] = useDrop<
    DragItem,
    void,
    { handlerId: Identifier | null }
  >(
    () => ({
      accept: DRAG_ITEM_TYPE.reorderableListItem,
      collect(monitor) {
        return {
          handlerId: monitor.getHandlerId(),
          item: monitor.getItem(),
        }
      },
      hover: (item: DragItem, monitor) => {
        if (!itemRef.current) {
          return
        }
        const dragIndex = item.index
        const hoverIndex = index

        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
          return
        }
        // Determine rectangle on screen
        const hoverBoundingRect = itemRef.current?.getBoundingClientRect()

        // Get vertical middle
        const hoverMiddleY =
          (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2

        // Determine mouse position
        const clientOffset = monitor.getClientOffset()

        // Get pixels to the top
        const hoverClientY = (clientOffset as any).y - hoverBoundingRect.top
        console.log('hoverClientY',hoverClientY)

        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%

        // Dragging downwards
        if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
          return
        }

        // Dragging upwards
        if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
          return
        }

        // Time to actually perform the action
        handleMove(item, hoverIndex)
        scroll(hoverClientY)
        // // Note: we're mutating the monitor item here!
        // // Generally it's better to avoid mutations,
        // // but it's good here for the sake of performance
        // // to avoid expensive index searches.
        item.index = hoverIndex
      },
    }),
    [handleMove, index, id, scroll],
  )
  const scroll = useCallback((lastMouseClientY: number) => {
    if (listRef.current) {
      const position = listRef.current?.getBoundingClientRect()
      const { top, bottom } = position
      const scrollSpeed = 5
      const margin = lastMouseClientY
      if (lastMouseClientY > bottom - margin) {
        console.log('down')
        const nextScrollTop = listRef.current.scrollTop + scrollSpeed
        listRef.current.scrollTo(0, nextScrollTop)
      } else if (lastMouseClientY < top + margin) {
        console.log('up')
        const nextScrollTop = listRef.current.scrollTop - scrollSpeed
        listRef.current.scrollTo(0, nextScrollTop)
      }
    }
  }, [])

I want to trigger scroll when I hover over container, but hover method from useDrop works only while hovering on another item. So, for example, if I will move item to the bottom with drag ( which will satisfy my coordinates condition ) it will be move item in the list and now instead of scroll to the bottom it will hover on itself ( not another item ) and hover will not be triggered ( no scroll )
Could you help me?

Get value of input type=date as a string

I want to extract the value from date field, but it doesn’t work. I add the input this way:

var question0  = "<div id='0'><p>Please, enter the date: </p><br>" 
                       + "<input type="date" id='contractdate'></input><br></div>";

Here is how I tried to receive the value:

var text_Contract_Date     = document.getElementById('contractdate').value;
//tried the code below, but didn't work
// var text_Contract_Date  = document.getElementById('contractdate').valueAsDate;
// var text_Contract_Date  = new Date(document.getElementById('contractdate').valueAsDate);

So, I want to get the value from input as a string, using pure JavaScript, because then it will be used to fill in the document.