How to initiate ojet menu from javascript

We are using below function in java script to trigger oj-dialog and its working fine.

else if(operation === "fmethod"){
            
            var popup = document.getElementById("fPopUp");
            if (!popup.isOpen()) {
                popup.open();
            }
            return;

But when I am using the same function to trigger oj-menu or any other oj element we are getting “popup.isOpen is not a funtion” error.

Can someone let me know what should be the equivalent syntax of javascript to trigger or start oj-menu.

Material UI – Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

how are you?

I have a React project with Webpack and Babel, and i’m trying to add Material UI (https://mui.com/) components, however, when i import a MUI component into my project i get the next error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

A workaround i found is to add the “.default” import, but i don’t understand why i’m not able to just import it the traditional way.

Here’s a test component code that produces the error:

const React = require("react");
const Button = require("@mui/material/Button");

const Navbar = () => {
  return <Button variant="contained">Contained</Button>;
};

module.exports = Navbar;

And here’s my .babelrc and webpack.config code:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  output: {
    path: path.join(__dirname, "/dist"),
    filename: "index.bundle.js",
  },
  devServer: {
    port: 8443,
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /.scss$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({ template: "./src/index.html" }),
    new MiniCssExtractPlugin(),
  ],
};

Does anyone know what i’m doing wrong? I know it might be silly, but i should be able to just import these components the “normal” way as stated in the MUI documentation, instead, i have to import them using the “.default” way.

Thanks in advance, sorry for my bad english.

Method “getChampionName” has type “undefined” in the component definition. Did you reference the function correctly?

im trying to use this function (src/api/)

function getChampionName(champId) {
  axios.get('http://ddragon.leagueoflegends.com/cdn/12.5.1/data/en_US/champion.json')
    .then(({ data }) => {
      let list = data
      let championList = list.data
      for (var i in championList) {
        if (championList[i].key == champId) {
          return championList[i].id
        }
      }
    })
    .catch((err) => console.log(err))
}

export {getChampionName}

in this component (src/components/)

<template>
  <div class="w-72">
    <header class="rounded-tl-lg rounded-tr-lg bg-slate-400 p-0.5">
      <p>Champion's Mastery</p>
    </header>
    <ul class="grid gap-1 rounded-bl-lg rounded-br-lg bg-slate-50 p-0.5">
      <li v-for="champ in masteryData.slice(0,10)" :key="champ.championId">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <img src="https://ddragon.leagueoflegends.com/cdn/12.5.1/img/champion/Karma.png" alt="" class="rounded-lg h-14 w-14">
            <div>
              <p class="font-medium text-center">{{ getChampionName(champ.championId) }}</p>
              <p>Level {{ champ.championLevel }}</p>
            </div>
          </div>
          <p class="text-2xl font-medium">{{ champ.championPoints }} Pts</p>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import getChampionName from '@/api/search'

export default{
  name: 'MasteryInfo',
  props: [
    'masteryData'
  ],
  methods: {
    getChampionName
  }
}
</script>

But im getting this error “Method “getChampionName” has type “undefined” in the component definition.” and dont know what it means

Unzipping the folder but getting this error

Unzipping the folder but getting this error.
TypeError [ERR_INVALID_ARG_VALUE]: The argument ‘path’ must be a string or Uint8Array without null bytes. Received “PKx03x04x14x00x00x00x00x00]pkTx00x00x00x00x00x00x00x00x00x00x00x00x0Ex00x00x00Documentation/PKx03x04…

            decompress(data.data.toString('utf8'), 'output', {
              plugins: [
                  decompressUnzip()
              ]
          }).then(() => {
              console.log('Files decompressed');
          });

(REACT.JS)How to increment a data in my component

class Personne extends React.Component {
// constructor(props){
//     super(props);
// }
birthdayHandler = () => {
    let Age = this.props.age;
    let ageToNumber = parseInt(Age);
}

render(){
    return(
       <Fragment>
         <div className={classes.maintitle}>
            <h1 style={Name}> {this.props.name}</h1>
            <div> Job : {this.props.job}</div>
            <AgePersonne age={this.props.age}/>
            <div> Sexe : <strong style={sex}>{this.props.sexe ? "Homme" : "Femme"}</strong></div>
            <button onClick={(event) => this.birthdayHandler(event)} style={Button}>Birthday</button>
         </div>
       </Fragment>
    )
}

}

I would like to increment the age of the person by clicking on the button.

the AgePersonne component looks just like this :

const agePersonne = (props) => {
    const now = new Date();
    const year = now.getFullYear();
    return(
        <div>Age : {props.age} - année de naissance :{year - props.age -1}</div>
    )
};`

I did it already in a parent component with a button, but it increments all of my person’s age.
The APP component looks like this :

class app extends Component {

state = {
  personne: [
    {name: "Andy GARCIA", age: "28", job:"Web Dev", sexe: true},
    {name: "Sylvie MOISAN", age: "60", job:"nurse", sexe: false},
    {name: "Benjamin BARIOHAY", age: "27", job:"Web Dev", sexe: true},
    {name: "Galina RAZLIVANOVA", age: "29", job:"Web Security consultant", sexe: false},
    {name: "Maxime GIRARDEAU", age: "28", job:"Sailer", sexe: true},
  ]
}
  render() {
      return (
        <Fragment>
          <Horloge />
          <Personne {...this.state.personne[0]}/>
          <Personne {...this.state.personne[1]}/>
          <Personne {...this.state.personne[2]}/>
          <Personne {...this.state.personne[3]}/>
          <Personne {...this.state.personne[4]}/>
        </Fragment>
      )
  }

}

could you help me please ? I’m really lost, thank you

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.