How to paste the content where cursor is there in content editable div

I am a newbie on react. I have a content editable div. What I want is Make a button, on button click -> “HEY” word will be added. Let’s say my content length is 100, and I have clicked on initial 5 character and giving the space and click my paste button. So the “HEY” content will be append in that position.

My code:

renderValue = () => {
 var textNode = document.createTextNode("HEY");
      let p1 = document.getElementById('work').focus();
      p1.appendChild(textNode)
}

render(){
<button onClick={() => this.renderValue()}>Paste</button>
<div id="work" onClick={(e)=>e.stopPropagation()}  
contentEditable 
onInput={this.emitChange}
dangerouslySetInnerHTML={{__html: this.props.html}}
>
</div>
}

I have tried to append the text but not getting luck.

Anny help is really appreciated. Thanks in advance.

when selecting input leave only it as an available option

I have an input with ngfor, it appears several options

<article *ngIf="layout=='esalpet'" class="filter-group">
<header class="card-header">
    <a href="#" data-toggle="collapse" data-target="#collapse_4" aria-expanded="true" class="">
        <i class="icon-control fa fa-chevron-down"></i>
        <h6 class="title">Marcas</h6>
    </a>
</header>
<div class="filter-content collapse show" id="collapse_4">
    <div *ngFor="let categ of filtro" class="card-body">
        <label class="custom-control custom-radio">
            <input (change)="filterMarcas($event)" class="custom-control-input" type="radio" id="5" name="marca"
                value="{{categ.marcaJ.marca}}" id="flexCheckChecked" />

            <div class="custom-control-label" id="5">{{categ.marcaJ.marca}}</div>
        </label>
    </div>
    <!-- card-body.// -->
</div>

when selecting some of the inputs, I would like only the input selected by the user to appear

follow my method i tried to do

filterMarcas(event){
this.slicedItems = this.slicedItems.filter(item => item.marcaJ?.marca === event.target.value  )
console.log(this.slicedItems)
this.filtro = this.slicedItems.filter((record, index) => this.filtro.findIndex(check => check.marcaJ?.marca === record.marcaJ?.marca) === index);
this.peso = this.peso.filter((record, index) => this.peso.findIndex(check => check.peso === record.peso) === index);


}

Is there a better method than this?

    this.filtro = this.slicedItems.filter((record, index) => this.filtro.findIndex(check => check.marcaJ?.marca === record.marcaJ?.marca) === index);

Selectpicker cancel change value event

Consider the following event:

$(`#selectpicker).on('change', function(){
if(condition) {} else 
{
  //canceel event change
}
});

How to cancel the change event based on specific condition therefore maintaining the same select picker value.

How to use absolute coords in pixijs

My question is about moving lines and rects using absolute coords.

  1. I created line:
const line = new PIXI.Graphics();
line.lineStyle(2, 0xffffff);
line.moveTo(100, 200);
line.lineTo(300, 200);
app.stage.addChild(line);

But if I will try to set coords by changing x/y it will be relative to created pos:

line.x = 200; // real x will be 300
line.y = 200; // real y will be 400

How should I move this line if i need to set absolute coords on view?
Should I always calc absolute coords using current?

  1. Same question about rect, I create it like this:
const blueBox = new PIXI.Graphics();
blueBox.beginFill(0x0000ff);
blueBox.drawRect(50, 50, 50, 50);
blueBox.endFill();
app.stage.addChild(blueBox);

If i will try to move it using x/y i will do same as line – x/y are relative, ok.
I can always draw rects at 0/0 point and then move them, but is it correct desigin, is there other way?

ReactJS kanban not dragging (@lourenci/react-kanban)

I’m trying to make a simple kanban board in react using this library ‘@lourenci/react-kanban’.

I’ve followed the example they proposed on the github page ( https://codesandbox.io/s/react-kanban-demo-nvjp3?file=/src/index.js:141-163) but the problem is that i can get the board but my cards can’t move. Like the draggable is not created.

import ContentBody from '../../components/layout/content-body';
import Sidebar from '../../components/layout/sidebar';
import TitleBar from '../../components/layout/titlebar';
import CircularProgress from '@mui/material/CircularProgress';
import Typography from '@mui/material/Typography';
import { Navigate, useParams } from "react-router-dom";

import kanbanService from '../../services/kanban.service';

import Board, { moveCard } from "@lourenci/react-kanban";
import "@lourenci/react-kanban/dist/styles.css";

const initialBoard = {
    columns: [
        {
          id: 1,
          title: "Backlog",
          cards: [
            {
              id: 1,
              title: "Card title 1",
              description: "Card content"
            },
            {
              id: 2,
              title: "Card title 2",
              description: "Card content"
            },
            {
              id: 3,
              title: "Card title 3",
              description: "Card content"
            }
          ]
        },
        {
          id: 2,
          title: "Doing",
          cards: [
            {
              id: 9,
              title: "Card title 9",
              description: "Card content"
            }
          ]
        },
        {
          id: 3,
          title: "Q&A",
          cards: [
            {
              id: 10,
              title: "Card title 10",
              description: "Card content"
            },
            {
              id: 11,
              title: "Card title 11",
              description: "Card content"
            }
          ]
        },
        {
          id: 4,
          title: "Production",
          cards: [
            {
              id: 12,
              title: "Card title 12",
              description: "Card content"
            },
            {
              id: 13,
              title: "Card title 13",
              description: "Card content"
            }
          ]
        }
      ]
};
  
export default function KanbanBoard({setShowLoader, showMessageError, showMessageSuccess}) {
    const { id } = useParams();
    const [isLoaded, setIsLoaded] = React.useState(true);
    const [error, setError] = React.useState(null);
    const [lists, setLists] = React.useState([]);
        
    const [board, setBoard] = React.useState(initialBoard);

    function onCardMove(card, source, destination) {
        const updatedBoard = moveCard(board, source, destination);
        setBoard(updatedBoard);
         
        console.log("----------");
        console.log(card);
        console.log(source);
        console.log(destination);
        console.log(updatedBoard);
      }

    const fetchBoard = async () => {
        kanbanService.getBoard(id)
        .then(
            (result) => {
                result = result.data;
                setIsLoaded(true);
                setBoard(result);
                fetchLists();
            },
            (error) => {
                setIsLoaded(true);
                setError(error);
            }
        )
    }

    const fetchLists = async () => {
        kanbanService.getLists(id)
        .then(
            (result) => {
                result = result.data;
                setIsLoaded(true);
                setLists(result);
            },
            (error) => {
                setIsLoaded(true);
                setError(error);
            }
        )
    }

    React.useEffect(() => {
        //setIsLoaded(false);
        //fetchBoard();
    },[])

    return(
        <>
            <Sidebar setShowLoader={setShowLoader}>
                <TitleBar title={board.board_name}>
                </TitleBar>
                <ContentBody usePadding={true}>
                {(error)  ? (
                    <div > 
                        <Typography variant="subtitle1" gutterBottom component="div" style={{color:"red"}}>
                            <strong>Errore:</strong> {error.message}
                        </Typography> 
                    </div>
                ):(
                    !isLoaded ? (
                        <div style={{padding:"30px"}}><CircularProgress /></div>
                    ) : (
                        <>
                            <Board 
                                onCardDragEnd={onCardMove} 
                                disableColumnDrag
                            >
                            {board}
                            </Board>
                        </>
                    )
                )}
                </ContentBody>
            </Sidebar>
        </>
    )
}

I’ve installed the npm package using the param –force because i think there’re some problems with react 18 . Maybe this might be the problem? But other users installed also on react 18 without troubles.

Do you have ideas? Thanks

just can’t wrap my head around this script, want to press a button on a webpage in js

Hope it’s not against the rules, this script is for pressing the like button on instagram but instagram, as so often, changes it’s layout, i tried to find the new parent node and button but it won’t click it.
there is a tutorial video on how to adapt the code and find the new elements but it just fails on me.

code is not from me but i guess it’s fine to tinker with it because it even is encouraged to fix it yourself

Link to github:

https://github.com/frxangelz/ig_autolike_and_comment

How do I retrieve information from a generated list using an API

In my current code, I am trying to retrieve the “i” number generated by my list(function appendData(data)) and through this “id” of the list, I retrieve the “id” of the data from the API. And in a second time, to send this “id” to a php which processes the information. The concern I currently have is how do I get the “id” generated by the list, and how do I link it to the .json one?

part of my index.html who hosts the generated list :
<div id="myData"></div>

My script with fetch request to catch data from API :

fetch('http://www.my-api.com/php/get_people.php')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data);
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });

My function to generate a list with the data from the API:

function appendData(data) {
            var mainContainer = document.getElementById("myData");
            const button = document.querySelector('button');
            for (var i = 0; i < data.length; i++) {
                var div = document.createElement("div");
                div.innerHTML = '<p><strong>Nom : </strong>' + data[i].name + '<br><strong>Entreprise : </strong>' + data[i].company + '<br><strong>Personne visitée : </strong>' + data[i].person_visited + '<br><strong>Date : </strong>' + data[i].date + '<br><button onclick="delete_visit()"> Mettre fin à la visite</button>' + '</p>';
                mainContainer.appendChild(div);

            }
}

And the last function, which is experimental, which does not work. Which confirms the sending of the ID to php :

        function delete_visit() {
            let x = document.getElementsByClassName('myData');
            let name = document.getElementsByClassName('myData').value;
            alert('Confirmer la fin de la visite de Monsieur/Madame ' + name + ' ?');
        }

I am new to this environment, and I know that several problems arise in my code. Thanks for your answer and explanation.

D3 tooltip in Bar Chart: Unable to get it working

I have tried everything but the tooltip doesn’t work. I copy pasted someone else’s code and the tooltip worked but when I wrote my code for tooltips the same way it doesnt work. Here is my full code:

**//getting the data**
async function getdata() {
  const url = await fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json')
  .then(res => res.json())
  .catch(err => console.log(err));
  
  
  const data = url.monthlyVariance;
  const basetemp = url.baseTemperature;
  
  const w = 1300;
  const h = 1000;
  const p = 100;
  
**//the svg shape**
  const svg = d3.select('#map')
  .append('svg')
  .attr('id', 'svg')
  .attr('width', w)
  .attr('height', h);
  
**//labels for x and y axis**
  svg.append('text')
  .attr('transform', 'rotate(-90)')
  .attr('x', -500)
  .attr('y', 50)
  .style('font-size', '20px')
  .style('fill', '#1d3557')
  .text('Variance')
  
  svg.append('text')
  .attr('x', w/2 + (-50))
  .attr('y', h-50)
  .style('font-size', '20px')
  .style('fill', '#1d3557')
  .text('Years (1753-2015)')


***//TOOLTIPS***   
  const tooltip = d3.select('#map')
  .append('div')
  .attr('id', 'tooltip')
  .style('visibility', 'hidden')
  .style('width', '150px')
  .style('padding', '10px')
  .style('height', '60px')
  .style('opacity', 1)
  
  const ttyear = d3.select('#tooltip')
  .append('div')
  .attr('id', 'ttyear')
  .attr('width', '150px')
  .attr('height', '40px')
  
  const ttmonth = d3.select('#tooltip')
  .append('div')
  .attr('id', 'ttmonth')
  .attr('width', '150px')
  .attr('height', '40px')
  
  const ttvar = d3.select('#tooltip')
  .append('div')
  .attr('id', 'ttvar')
  .attr('width', '150px')
  .attr('height', '40px')
  
**//x and y scale**
  const xscale = d3.scaleLinear()
  .domain([1752, 2016])
  .range([p, w-p]);
  
  const yscale = d3.scaleLinear()
  .domain([d3.min(data, (d) => d.variance + basetemp), d3.max(data, (d) => d.variance + basetemp)])
  .range([h-p, p]);
  
**//the main graph/plot**
  svg.selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('width', '1.5px')
  .attr('height', (d) => h-yscale(d.variance + basetemp) - p)
  .attr('fill', '#e63946')
  .attr('x', (d) => xscale(d.year))
  .attr('y', (d) => yscale(d.variance + basetemp))

**//code for tooltip that doesnt work**
  //.append('title')
  //.text((d) => `Year: ${d.year}, Month: ${d.month}, Variance: ${d.variance + basetemp}`)
  .on('mouseover', (d) =>{
    d3.select('#tooltip')
    .style('visibility', 'visible')
    .style('left', event.pageX-25 + 'px')
    .style('top', event.pageY-75 + 'px')
    
    d3.select('#ttyear')
    .text(`Year: ${d.year}`)
    
    d3.select('#ttmonth')
    .text(`Month: ${d.month}`)
    
    d3.select('#ttvar')
    .text(`Variance: ${d.variance}`)
  })
  .on('mouseout', (d)=>{
    d3.select('#tooltip')
    .style('visibility', 'hidden')
  })
  

**//x and y axis**
  const xaxis = d3.axisBottom(xscale);
  svg.append('g')
  .attr('transform', `translate(0, ${h - p})`)
  .call(xaxis);
  
  const yaxis = d3.axisLeft(yscale);
  svg.append('g')
  .attr('transform', `translate(${p}, 0)`)
  .call(yaxis);
  
  
}
getdata()

Basically following is the code for tooltip:

const tooltip = d3.select('#map')
  .append('div')
  .attr('id', 'tooltip')
  .style('visibility', 'hidden')
  .style('width', '150px')
  .style('padding', '10px')
  .style('height', '60px')
  .style('opacity', 1)
  
  const ttyear = d3.select('#tooltip')
  .append('div')
  .attr('id', 'ttyear')
  .attr('width', '150px')
  .attr('height', '40px')
  
  const ttmonth = d3.select('#tooltip')
  .append('div')
  .attr('id', 'ttmonth')
  .attr('width', '150px')
  .attr('height', '40px')
  
  const ttvar = d3.select('#tooltip')
  .append('div')
  .attr('id', 'ttvar')
  .attr('width', '150px')
  .attr('height', '40px')

and

.on('mouseover', (d) =>{
    d3.select('#tooltip')
    .style('visibility', 'visible')
    .style('left', event.pageX-25 + 'px')
    .style('top', event.pageY-75 + 'px')
    
    d3.select('#ttyear')
    .text(`Year: ${d.year}`)
    
    d3.select('#ttmonth')
    .text(`Month: ${d.month}`)
    
    d3.select('#ttvar')
    .text(`Variance: ${d.variance}`)
  })
  .on('mouseout', (d)=>{
    d3.select('#tooltip')
    .style('visibility', 'hidden')
  })

I tried using the other simpler method for tootltip (the ‘title’ and text method) and it works.
Please help. Thank you in advance.

Inline Raw SVG has worse quality than when placed in tag

I am creating SVGs directly in the client. Therefore, in my Javascript in the client I am creating the raw SVG and manipulating it depending on the user input.
I took the raw SVG and placed it in a file and then displayed that SVG file right next to the raw inline SVG. The result was much more crispy.
Here is the raw inline SVG:
RAW INLINE SVG

Compare this to the SVG when placed in a file and using an tag:
SVG INSIDE IMG TAG

As you can see the quality varies a lot!

Here is a codepen link so that you can directly grab the raw SVG if you would like to perform tests: https://codepen.io/fabiansvensson/pen/WNMJpQr

<html>
<body>
<!-- THE RAW SVG -->
<svg></svg>
</body>
</html>

Importantly, I did notice that the quality seems to be better in the codepen, which leads me to think that perhaps the problem has something to do with the styling of the page. I haven’t been able to find any reason why this might be. I am considering writing the raw SVG directly to file (not ideal) or somehow making the styling of the SVG independent from the rest of the page (e.g. iFrame).

Any ideas what might be causing this and how to solve the problem?

run angular when used ng build –prod –aot

Angular version of my project

"@angular/cdk": "^11.2.9",
"@angular/common": "^11.2.10",
"@angular/compiler": "^11.2.10",
"@angular/compiler": "^11.2.10",
"@angular/core": "^11.2.10",
"@angular/localize": "^11.2.10",
"ts-node": "9.1.1", 
"typescript": "^4.1.5"
////////////////
"nodeVersion" : "14.16.1"
"npmVersion" : "6.14.12"

My project dependencies are package.json

enter image description here

I get the following error when I use the ng build –prod –aot command

enter image description here

I searched for this error and came across this link

According to the instructions they gave, I used these commands to re-install the packages according to the Angular version

I used these commands

npm uninstall tailwindcss

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

After running the commands, I ran the ng build –prod –aot command again

enter image description here

Now the error he gave me is a little different and relates to this link

Now our friends say that something has to be disabled so that this process might work

enter image description here

Now I do not know if this solution is correct or not but I am looking for a better solution that I can use the ng build –prod –aot command

Please, if you think a better solution, please help me

Hey, So I am an amateur using chartjs and I want to know how to pass a nested function to an HTML button and Dropdown menu

I have two major functions getChart() and fetchdata() and they get the chart data and my x and y axes data from database respectively. I want to use a function inside my getChart for my dropdown menu to display different types of charts when clicked on them. Can someone help me out. Thanks

<body>
<div class="chartMenu">
    <p>Loan Applications Accepted</p>
    <div class="chartCard">
        <div class="chartBox">
            <canvas id="myChart"></canvas>
            
            <button onclick="(new getChart()).back();"> GO BACK </button>
            <select onchange="(new start()).changeChart();">
                <optgroup label="Select Chart"></optgroup>
                <option value="bar">Bar</option>
                <option value="pie">Pie</option>
                <option value="line">Line</option>
                 <option value="doughnut">Doughnut</option>
              </select>

function fetchData(url) {
$.ajax({
url: url,
type: “GET”,

                    success: function (data) {
                        coordinates = [];
                        // console.log(data);
                        Array.from(data).forEach(element => {
                            coordinates.push({ x: element.x_axis, y: element.y_axis })
                            console.log(coordinates)

                        });


                        getChart();

                    },

                    error: function (error) {
                        console.log(`Error ${error}`);
                    }
                });






            };

function getChart() {

      //setup block
      var data = {

        datasets: [{
          label: 'No of Loan Applications',
          data: coordinates,

          backgroundColor: [
            'rgba(193, 32, 32, 0.58)',
            'rgba(75, 192, 192, 0.58)',
            'rgba(255, 159, 64, 0.58)',
            'rgba(153, 167, 64, 0.58)',
            'rgba(153, 102, 255, 0.58)',
            'rgba(255, 159, 64, 0.58)',
            'rgba(0, 0, 0, 0.58)',
            'rgba(167, 40, 145, 0.58)',
            'rgba(0, 184, 223, 0.58)',
            'rgba(70, 216, 59, 0.58)',
            'rgba(255, 231, 59, 0.58)',
            'rgba(18, 228, 184, 0.58)'



          ],
          borderColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(255, 159, 64, 1)',
            'rgba(75, 192, 192, 0.8)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(0, 0, 0, 0.2)',
            'rgba(167, 40, 145, 0.8)',
            'rgba(0, 184, 223, 0.8)',
            'rgba(70, 216, 59, 0.54)',
            'rgba(255, 231, 59, 0.86)',
            'rgba(18, 228, 184, 0.59)'
          ],
          borderWidth: 1
        }]

      };

      //config block
      var config = {
        type: 'bar',
        data,
        options: {

          scales: {
            y: {
              beginAtZero: true,
              grace: 1,
              ticks: {

                precision: 0,


              }

            },


          },

        }


      };


      //render block
      var ctx = document.getElementById('myChart');

      let myChart = new Chart(
        ctx,
        config

      );



      this.back = function () {
          if (myChart != null) {
              myChart.destroy();
          }
          fetchData('http://localhost:8080/jsonGet?year=1')
          myChart.data.datasets[0].data = coordinates;
          myChart.update();
      };


      function clickHandler(click) {


        const points = myChart.getElementsAtEventForMode(click, 'nearest', { intersect: true }, true);
        if (points.length) {
          const firstPoint = points[0];
          console.log(firstPoint.element.$context.raw.x)

          if (firstPoint.element.$context.raw.x == "2020") {

            fetchData('http://localhost:8080/jsonGet?year=2020')
            myChart.data.datasets[0].data = coordinates;
            myChart.update();



          }

          else if (firstPoint.element.$context.raw.x == "2021") {

            fetchData('http://localhost:8080/jsonGet?year=2021')
            myChart.data.datasets[0].data = coordinates;
            myChart.update();

          }

          else if (firstPoint.element.$context.raw.x == "2022") {

            fetchData('http://localhost:8080/jsonGet?year=2022')
            myChart.data.datasets[0].data = coordinates;
            myChart.update();

          }



          else {
            console.log("Wrong input");
          }

        }
      };
      ctx.onclick = clickHandler;

      function changeChart(chartType) {
        console.log(chartType);
        console.log(chartType.value);
      }

      function start() {
        getChart();
        clickHandler(click);
        changeChart(chartType)
      }

      start();

    };

    $(document).ready(fetchData(url));