Positioning options menu directly under highlighted text

I’m trying to show the user a pop up menu with some options if they highlight any text in the browser. I want the menu to be displayed directly under the highlighted text.

I am currently using getBoundingClientRect() on the range of the text. Passing the object to the menu and using the coordinates to set the positioning.

function doSomethingWithSelectedText() {
    let selectedText = getSelectedText();
    let sel;
    if (selectedText && selectedText.indexOf(' ') === -1) {
        console.log('SELECTED TEXT =>', selectedText)
        sel = window.getSelection();
        if (sel.rangeCount) {
            let range = sel.getRangeAt(0);
            let coords = range.getBoundingClientRect()
            setTimeout(() => { handleShowMenu(coords) }, 800)
        }

    }
}
const handleShowMenu = (coords) => {

    menu.style.display = 'block'
    menu.style.left = coords.x + 'px'
    menu.style.top = coords.y + 'px'
}

During some highlighting tests of various text elements I notice:

  • The menu is positioned right under the <p> tags perfectly as to my desire.
  • The menu is positioned under the <h3> but closer to the top, almost overlapping the text.
  • The menu is positioned right under the <h1> but now partially overlapping the bottom of the text.

Any reason for this behavior, as well as a possible solution? thanks.

How to solve this DiffType function?

I’m trying to do a JavaScript challenge here, I was wondering if someone can guide me as I am very new to JS:

function diffTypes(arr){
}

Here is my attempt:

const diffTypes = arr => {
  let int = 0;
  let string = 0;
  let boolean = 0;
  let array = 0;
  let object = 0;

  for (let i = 0; i < arr.length; i++){
    if (typeof arr[i] === 'number'){
      int += 1
    } else if(typeof arr[i] === 'string') {
      string += 1
    } else if(typeof arr[i] === 'boolean') {
      boolean += 1
    } else if(typeof arr[i].constructor() === '[]') {
      array += 1
    } else if(typeof arr[i] === 'object') {
      object += 1
    }
  }
  let totalTypes = {
    string: string,
    array: array,
    boolean: boolean,
    object: object,
    number: int
  }
  return totalTypes
}

const ar = [
  1,
  "str",
  false,
  { name: 'Peter', age: 30 },
  ["a", "e", "i", "o", "u"],
  ]

console.log(diffTypes(ar))

However I am getting { string: 1, array: 0, boolean: 1, object: 2, number: 1 }

The end goal is to achieve this result:

console.log(diffTypes(ar))// => { string: 1, array: 1, boolean: 2, object: 1, number: 1 }

I am aware that typeof(arr) will = ‘Object’ so I tried to find different ways to += array.

When i was a GATSBY Build, i get 2 errors

This is my Gatsby Blog GitHub Link

When i work build i get 2 errors.

  1. The field "Mdx.excerpt." was explicitly defined as non-nullable via the schema customization API (by yourself or a plugin/theme). This means that this field is not optional and you have to define a value. If this is not your desired behavior and you defined the schema yourself, go to "createTypes" in gatsby-node.js. If you're using a plugin/theme, you can learn more here on how to fix field types:

  1. An error occurred during parallel query running.

When i was get build, gatsby give me some suggestions for my errors in this terminal.

Suggestion For first error

Suggestion for Second Error

How can i these fix.?

For the run my project, in this terminal

First step: npm install

Second Step: npm run dev

How to update the display using .map function in React.js

I have a useState variable that holds log data and I’m displaying that data using .map(), at some particular moment, logs will be added, and I take the old variable and re affect the new value for it as the following :

const [logs, setLogs] = useState([])

const function1 = () => {
// some process here
 setLogs(myValues)
}
const function2 = () => {
// some process
let myNewValues = logs
// some other process
setLogs(myNewValues)
}

.map() function displays the logs just fine after the first function, but when I update the logs with setLogs in the second function, .map() doesn’t get the update, it displays the old values from function1.

How can I fix this in react ?

Thanks in adavance !

SyntaxError: Invalid or unexpected token in Visual Studio Code while using Lit

Sadly I’m aware this question has been asked before, but I’ve tried the solutions here to no avail:
Uncaught SyntaxError: Invalid or unexpected token in code

I’ve reinstalled node.js, reinstalled lit.dev using npm, and reinstalled Visual Studio Code entirely. I’ve also written a separate, simple “hello world” program to test that there were no issues unrelated to the program itself and it worked fine.

I’m new to JS, node.js/npm, and to lit in general so I’m going to explain what I did exactly to see if there’s something missing. I created a folder to hold my project, opened cmd within it and added lit using npm i lit. I generated my package.json using npm init and generated my index.html and app.js files using VS Code. I tried to test it using the default example in https://lit.dev/playground/ and simply copied/pasted both the js and html code into my files. I will re-add them here for completion’s sake.

My html file contains:

<!DOCTYPE html>
<head>
  <script type="module" src="app.js"></script>
</head>
<body>
  <simple-greeting name="World"></simple-greeting>
</body>

My js file contains:

import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  static styles = css`p { color: blue}`;

  @property()
  name = 'Somebody';
  render() {
    return html`<p>Hello, ${this.name}!</p>`;
    debugger
  }
}

To test it I tried to run app.js but I keep receiving this error:

SyntaxError: Invalid or unexpected token
    at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:115:18)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:289:14)
    at async link (node:internal/modules/esm/module_job:70:21)

Wondering if there were hidden characters like in the previous thread, I then deleted all of the text I copied/pasted from the playground and manually retyped it in, but still receive the same error. Clicking it also gives me this error:

No debugger available, can not send 'variables'

I editted my launch.json file to have the following:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "console": "integratedTerminal",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\app.js"
        }
    ]
}

and I’m still unable to click the error for more details.

Is there something I’m doing wrong with the basic setup of the project? Or is there some other issue causing this?

I am trying to move a div by mouse on drag in Typescript React

This is the Code. But the window is moving away from the mouse after the first click.
How can I improve this code to make it clean and work?

import { BsCircle } from "react-icons/bs";
import { useState, useEffect, useRef, useCallback } from "react";

type Coordinates = {
  x: number;
  y: number;
};

const Index = () => {
  const [Mouse, setMouse] = useState<Coordinates | undefined>(undefined);
  const [newPosition, setNewPosition] = useState<Coordinates | undefined>(
    undefined
  );
  const [isMoving, setIsMoving] = useState(false);
  const [hasMoved, sethasMoved] = useState(false);
  const windowRef = useRef<HTMLDivElement>(null);
  const stylewindowContainer = hasMoved
    ? {
        top: newPosition?.y,
        left: newPosition?.x,
        position: "fixed" as "fixed",
        width: '37.5%',
        transform: 'none'
      }
    : { color: "black" };

    const startMoving = useCallback((e: MouseEvent) => {
      const Target = e.target as HTMLDivElement;
      setIsMoving(true);
      sethasMoved(true);
      setMouse({
        x: e.clientX - Target.getBoundingClientRect().left,
        y: e.clientY - Target.getBoundingClientRect().top,
      });
      if (Mouse) {
      setNewPosition({x: e.clientX - Mouse?.x, y: e.clientY - Mouse?.y})
    }}, [])

  useEffect(() => {
    if (!windowRef.current) {
      return;
    }
    
    const window: HTMLDivElement = windowRef.current;
    window.addEventListener("mousedown", startMoving);
    return () => {
      window.removeEventListener("mousedown", startMoving);
    };
  }, [startMoving]);
  
  const Moving = useCallback((e: MouseEvent) => {
    if (Mouse) {
      if (isMoving) {
        
    setNewPosition({x: e.clientX - Mouse?.x, y: e.clientY - Mouse?.y})
  }}}, [Mouse, isMoving]);
  
  useEffect(() => {
    if (!windowRef.current) {
      return;
    }
    const window: HTMLDivElement = windowRef.current;
    window.addEventListener("mousemove", Moving);
    return () => {
      window.removeEventListener("mousemove", Moving);
    };
  },[Moving]);

  const stopMoving = useCallback(() => {
    setIsMoving(false)
  },[])
  
  useEffect(() => {
    if (!windowRef.current) {
      return;
    }
    const window: HTMLDivElement = windowRef.current;
    window.addEventListener("mouseup", stopMoving);
    return () => {
      window.removeEventListener("mouseup", stopMoving);
    };
  },[stopMoving]);

  return (
    <>
      <div className="IndexFirstView">
        <div className="IndexFirstViewContainer">
          <div className="IndexHeading">
            <p>
              <span></span>
              <span>
                
              </span>
            </p>
            <p>
              <span></span>
              <span id="name">something</span>
              <span>,</span>
            </p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
            <p id="jobTitle">Hello World!</p>
          </div>
          <div className="rightSide">
            <div
              style={stylewindowContainer}
              className="windowContainer"
              ref={windowRef}
            >
              <div className="topbar">
                <div className="windowBtns">
                  <span id="windowBtn">
                    <BsCircle />
                  </span>
                  <span id="windowBtn">
                    <BsCircle />
                  </span>
                  <span id="windowBtn">
                    <BsCircle />
                  </span>
                </div>
              </div>
              <div className="windowBottomContainer">
                <p>Hello World!</p>
                <p>
                  <br />
                </p>
                <p>
                  {newPosition?.x} : {newPosition?.y}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="IndexSecondView">
        <p>Hello World!</p>
      </div>
    </>
  );
};

export default Index;

My initial logic was to get the position of mousedown inside the window to get the relative position of the point where we can hold the window. store those coordinates in the Mouse and then update the position of the box with respect to the mousemove event coordinates subtracting the intitial Mouse Coordintes. It doesnt seem to work.

is it possible to remove the transparent part of an image using CANVAS and Javascript?

Hi so for example this image https://e7.pngegg.com/pngimages/433/468/png-clipart-white-heart-shape-illustration-heart-outline-wedding-hearts-love-angle.png

Is it possible to remove the transparent part of the image using CANVAS and JS? And by removing I mean the it’ll cut or crop image so the transparent part will be removed to the image? I haven’t a sample code to share, I tried to look it online, but I really got any answers from the search results I made.

Vue.js – why is my debounce function not working with arrow function

Here is my debounce function:

function debounce(fn, wait = 1500) {
  let timeout;
  return function (...args) {
    if (timeout) clearTimeout(timeout);
    let context = this;
    timeout = setTimeout(function () {
      fn.apply(context, ...args);
    }, wait);
  };
}

Here is my method in the component:

methods: {
    onKeyUp() {
      if(this.q.length) this.isLoading = true; // show loading spinner
      return debounce(() => this.querySearch())()
    },

So I have to execute the debounce call with an extra set of () which makes sense, because debounce returns a function. Now, if I change it to this:

methods: {
    onKeyUp: debounce(function() { 
       this.querySearch()
    })

I don’t understand why this works – debounce returns a function. I would expect when onKeyUp is triggered, it would run debounce – which just returns a function, without ever executing it. Does it implicitly execute the returned function with this syntax? Why?

Also, why does it need to be a non-arrow function in the second example? I know in the first example you want an arrow fn because you want this to point to the component context, but im unclear why using this key-value syntax breaks that down here.

Javascript ES6 confusion [duplicate]

I ran across some code this week that has me very confused. Can someone break down for me exactly what’s going on, line-by-line?

new Date(
  (d => d.setMonth(d.getMonth() - 6))(
    new Date()
  )
)

I understand it’s creating the current date minus six months (which I didn’t expect to work in all cases, but that is an aside). In particular, I don’t understand two things:

a) The variable d. Does this represent the new Date that’s being created on line 1?

b) The second new Date() on line 3. Is d.setMonth() returning a function and new Date() is the parameter?

Thanks in advance!

await doesn’t wait before moving onto next line of code

My code:

async function main(collection, token, symbol) {
  await collection.deleteMany({});
  const priceHistory = await makePriceHistoryRequest(token, symbol, slow*2);
  await insertPriceHistory(collection,priceHistory);
  const res = await priceQuote(token,symbol);
  await insertQuote(collection,res,symbol);
  return await avgFastSlow(fast,slow,collection);
}

My code makes request to 2 endpoints and update MongoDB collection. The last code:

return await avgFastSlow(fast,slow,collection);

takes the updated collection from the two endpoints to calculate fast and slow average. Problem is that it is not waiting before moving onto the this last line of code. Isn’t the point of async function to make it “wait?”

Mystified here. Thanks for the help

CORS issue with localhost despite proxy

I have created a REST API for the backend of this project and am using React to make the client side of the app. I have been getting this error when I am trying to login to my app.

Access to XMLHttpRequest at ‘https://studioghiblidb.herokuapp.com/login’ from origin ‘http://localhost:1234’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I was advised to include the local host as a proxy which I did in my client side package.json like this

"devDependencies": {
    "@parcel/transformer-sass": "^2.3.2",
    "process": "^0.11.10"
  },
  "proxy" : "http://localhost:1234/"

On the server side I was instructed to use this code to keep from cross site forgery issues. I have included the essentials as accepted origins

const cors = require('cors');

 let allowedOrigins = [
'http://localhost:8080', 
'http://testsite.com',
'http://localhost',
'http://localhost:1234',
'https://studioghiblidb.herokuapp.com/'
];

app.use(cors({
  origin: (origin, callback) => {
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
       let message = 'The CORS policy for this application does not allow found on the list of allowed origin' + origin;
       return callback(new Error(message), false);
  }
  return callback(null, true);
}
}));

I am at a complete loss as to what is causing the CORS error to keep from giving a JWT token and logging in. I have tested in Postman and the users are there and working

node express chart js data parsing/rendering issue

Excel Data

Date    Percentage
04-03-22 (H)    80
05-03-22 (H)    55
06-03-22 (H)    20
07-03-22 (H)    49
08-03-22 (H)    61
09-03-22 (H)    73
TODAY (P)   23
11-03-22 (P)    64

Controller code

datavCenterSpacePredictionModelData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[3]]); 

Passing this object to view

await res.render('dashboard', { vCenterSpace:datavCenterSpacePredictionModelData})

In my view I am not able to parse/loop through this data so that it can be passed on to chartjs object.
Chart object need labels and data

const zschart = new Chart(document.getElementById("chartjs-0"), {
                                    "type": "line",
                                    "data": {
                                        "labels": ["04-03-22 (H)","05-03-22 (H)","06-03-22 (H)","07-03-22 (H)","08-03-22 (H)","09-03-22 (H)","TODAY (P)","11-03-22 (P)","12-03-22 (P)","13-03-22 (P)","14-03-22 (P)","15-03-22 (P)"],
                                        "datasets": [{
                                            "label": "Usage in %",
                                            "data": [80,55,20,49,61,73,23,64,60,91,70,95],
                                            "fill": false,
                                            "borderColor": "rgb(75, 192, 192)",
                                            "lineTension": 0.1
                                        }]
                                    },
                                    "options": {}
                                });

when I am trying to get this value, is returning me object. I am checking type of object it is returning me string

var vCenterSpace = ('<%=vCenterSpace%>') //value of node js object into JS
alert(typeof(vCenterSpace ))

I want to dynamically pass these value as below.
These are hardcoded values

"labels": ["04-03-22 (H)","05-03-22 (H)","06-03-22 (H)","07-03-22 (H)",
"data": [80,55,20,49,61,73,23,64,60,91,70,95],

Its all getting messed up, not able to understand how this resolve this.

Is there a way to keep an element inside the boundaries of a div while still having it be position: absolute?

I have an element that displays a tooltip when hovered over, but when the element is on the edge of the screen, the tooltip gets cut off instead of moving to stay in the div.

What it looks like (Tooltip Clipping)

What I want it to look like

Here’s some of my code:

<div class="image">
    <img src="/images/image_name.png" style="left: 100%">
    <span class="tooltiptext">Marker</span>
</div>
.image {
  position: absolute;
  width: 13px;
  height: 13px;
  user-select: none;
  pointer-events: auto;
  transform: translateX(-50%);
}

.image .tooltiptext {
  visibility: hidden;
  opacity: 0;
  transition: opacity 300ms;

  min-width: 90px;
  background-color: #000000e0;
  color: white;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  
  position: absolute;
  z-index: 2;
  bottom: 100%;
  left: 50%;
  transform: translate(-90%, -5px);
}

.image:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}

Let me know if there’s a way to fix this!
Thanks!