How to have a box inside the current page to show output?

My Chrome extension copy text from the current page and show that inside a box on the left side of the current page, which will remain fixed even if I scroll the current page. My code is:

content.js

string=[];i=0;
function doc_keyUp(e) {
if (getSelectionText() != "")  {
if (e.key === '1') {
                   string[i]=string+getSelectionText(); 
                    view = window.open("","Viewer", "width=400,height=600"); //"_parent",   
                    
                    edit = document.createElement("div");   
            
                    edit.textContent = "Arranging Text.nn"+string;    
                    view.document.body.appendChild(edit);                   
                   } 
                                }
                      } // doc_keyUp(e)
console.log('The program has started!!!');  
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);                              

function getSelectionText() {
    var text = "";
     text = window.getSelection().toString();
    if (window.getSelection) {
        text = window.getSelection().toString();
    } 
    else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;    
}   
                                               
                                               

manifest.json

{
  "name": "",
  "description": "",
  "version": "1.0",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "permissions": ["tabs"]
}   

Now I have a window which pops up, but I want to have that window inside the current page. For example see the below image:

enter image description here

See the “B” is the current page, and “A” is another part that will remain same even if you scroll “B”. I want to show in box like “A”.

What is the name of such things? How can I do that?

how to convert the json object of array to json object of object in javascript

I have a JSON array or may be payload which is object of JSON array,

{
    "key": "value",
    "key2": "value2"
    "myids": [
        {
            "key": "value",
            "num": 123,
            "label": "equal"
        }
    ]
}

but need to change this payload to just below JSON object of JSON object

{
    "key": "value",
    "key2": "value2"
     "myids": {
        "myid": {
            "key": "value",
            "num": 123,
            "value": "equal"
        }
    }
}

any kind of help of would be grateful…

How can I make the comma disappear?

I’m very new to JS, and I dont know how to get rid of the “,” between my HTML elements (the ones that were add by .innerHTML)

Here’s my JS code :

let meubleData = []

const fetchProduct = async () => {

    await fetch('http://localhost:3000/api/products')
      .then((res) => res.json())
      .then((res) => {
        console.log(res.length)
        meubleData = res
        console.log(meubleData)
      }
      )
  }

fetchProduct()


const displayProduct = async () => {
    await fetchProduct()
    document.getElementById('items').innerHTML = meubleData.map((meuble) => 
            `<a href="./product.html?_id=${meuble._id}">
                <article class = "article">
                    <img class="item__img" src = "${meuble.imageUrl}" alt = "${meuble.altTxt}" />
                    <h3 class="productName">${meuble.name}</h3>
                    <p class="productDescription">${meuble.description}</p>
                </article>
            </a>`
     
    )
    }

displayProduct()```

The problem is, between each new links created, there is a comma. I tried splice / slice, without success…
Could you please help me ?

Thanks in advance for your answers and your time !

Javascript to perform custom placement of svg text

I am working with a SVG element as following. In this I am using <textPath></textPath> to place a text on a path.

The svg is following

<!DOCTYPE html>
<html>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
      <rect class="vBoxRect" width="1280" height="720" fill="green" rx="35" style="overflow: visible;"></rect>
      <rect class="boundRect" x="70" y="70" width="1090" height="500" fill="green"></rect>
      <g class="bound" style="transform: translate(70px, 70px);">
        <path id="WorldAvg" class="WorldAvg" fill="none" stroke="white" stroke-width="5" opacity="1" d="M0,418.8448266855795L45.416666666666664,414.575606092466L90.83333333333333,411.52106545918446L136.25,407.6362492744353L181.66666666666666,404.77160362539087L227.08333333333334,393.4071256244998L272.5,391.02044947895274L317.9166666666667,386.66829128561017L363.3333333333333,379.8367479839252L408.75,378.1893224105598L454.1666666666667,369.95354728799214L499.5833333333333,368.77725419172447L545,363.8472517451793L590.4166666666666,363.6062134379884L635.8333333333334,357.4943259634553L681.25,351.27652154825586L726.6666666666666,344.34458188257486L772.0833333333334,342.18836536625594L817.5,338.5473949587725L862.9166666666666,336.1670218633692L908.3333333333334,332.6090887556393L953.75,328.1112436453848L999.1666666666666,321.4448005003716L1044.5833333333335,312.9573561957251L1090,306.4131526885112"></path>
        <g class="avgLbl">
          <text text-anchor="start" stroke="red">
            <textPath href="#WorldAvg" startOffset="0%">10.3%</textPath>
          </text>
          <text text-anchor="end" stroke="red">
            <textPath href="#WorldAvg" startOffset="100%">24.7%</textPath>
          </text>
        </g>
    </svg>
  </body>
</html>

My end goal is to place each text just above the path so that the text is clearly visible.
To achieve that, I tried the following which did not work. the label for 24.7% is pushed far down.

Is there a way to programatically achieve this?

const element = document.querySelectorAll('.avgLbl>text');
const comp = document.querySelector(`.bound>#WorldAvg`);
element.forEach(
    (a, i) => {
        const diff = comp.getBoundingClientRect().bottom - a.getBoundingClientRect().bottom;
        a.setAttribute('transform', `translate(0,${diff})`)
    }
);
<!DOCTYPE html>
<html>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
      <rect class="vBoxRect" width="1280" height="720" fill="green" rx="35" style="overflow: visible;"></rect>
      <rect class="boundRect" x="70" y="70" width="1090" height="500" fill="green"></rect>
      <g class="bound" style="transform: translate(70px, 70px);">
        <path id="WorldAvg" class="WorldAvg" fill="none" stroke="white" stroke-width="5" opacity="1" d="M0,418.8448266855795L45.416666666666664,414.575606092466L90.83333333333333,411.52106545918446L136.25,407.6362492744353L181.66666666666666,404.77160362539087L227.08333333333334,393.4071256244998L272.5,391.02044947895274L317.9166666666667,386.66829128561017L363.3333333333333,379.8367479839252L408.75,378.1893224105598L454.1666666666667,369.95354728799214L499.5833333333333,368.77725419172447L545,363.8472517451793L590.4166666666666,363.6062134379884L635.8333333333334,357.4943259634553L681.25,351.27652154825586L726.6666666666666,344.34458188257486L772.0833333333334,342.18836536625594L817.5,338.5473949587725L862.9166666666666,336.1670218633692L908.3333333333334,332.6090887556393L953.75,328.1112436453848L999.1666666666666,321.4448005003716L1044.5833333333335,312.9573561957251L1090,306.4131526885112"></path>
        <g class="avgLbl">
          <text text-anchor="start" stroke="red">
            <textPath href="#WorldAvg" startOffset="0%">10.3%</textPath>
          </text>
          <text text-anchor="end" stroke="red">
            <textPath href="#WorldAvg" startOffset="100%">24.7%</textPath>
          </text>
        </g>
    </svg>
  </body>
</html>

Collect key value pair from array of objects Javascript [closed]

I have an array of objects in Javascript and I want to collect just the given key and value from the list. How would one do this? I feel like I have over engineered the solution but maybe not.

I wasn’t sure if there was a cleaner way of doing this.

The results should be a list of objects containing just the key ‘id’ and id ‘value’.

const items = [{
    id: "45054",
    name: "Brittany"
  },
  {
    id: "8980",
    name: "Amber"
  },
  {
    id: "9843",
    name: "Leslie"
  },
  {
    id: "45306",
    name: "Doug"
  },
  {
    id: "7863",
    name: "Kevin"
  },
]

let ids = []

for (let i = 0; i < items.length; i++) {
  ids.push({
    id: items[i].id
  })
}

console.log(ids)

Hovering an article to make GatsbyImage scale

I want to scale the GatsbyImage whenever I hover a specific content , I am using this code to fetch multiple articles , and I want to hover them independently .

  {blog.data.blogs.map((ts)=>
 (
                <Blog to={`article/${ts.blog.document.uid}`}>
                <GatsbyImage  image={ts.blog.document.data.post_img.gatsbyImageData} alt='Blog' />
                <BlogTitle>
                {ts.blog.document.data.post_title.text}
                </BlogTitle>
                <BlogParagraph>
                {ts.blog.document.data.post_paragraph.text}
                </BlogParagraph>

How can I hover each article independently , and make the image scale if so ?

Using relative image path as parameter instead of using this

I’m trying to make an simple Tab Gallery based on the one found at W3Schools.

However I want to be able to use a relative image path instead of using ‘this’ when calling myFunction. But I don’t know how to do that.

As you can see in the Html, I have tried using a relative path for the second image, which doesn’t work. My structure is, index.html + main.css + script.js are all in the same folder and then I have a folder called ‘img’ for the images.

function myFunction(imgs) {
  // Get the expanded image
  var expandImg = document.getElementById("expandedImg");
  // Get the image text
  var imgText = document.getElementById("imgtext");
  // Use the same src in the expanded image as the image being clicked on from the grid

  expandImg.src = imgs.getAttribute("src");


  console.log(imgs.getAttribute("src"));
  // Use the value of the alt attribute of the clickable image as text inside the expanded image
  imgText.innerHTML = imgs.alt;
  // Show the container element (hidden with CSS)
  expandImg.parentElement.style.display = "block";
}

function closeExpandedImg(btn) {
  btn.parentElement.style.display = 'none';
}
* {
  box-sizing: border-box;
}


/* The grid: Four equal columns that floats next to each other */

.column {
  float: left;
  width: 25%;
  padding: 10px;
}


/* Style the images inside the grid */

.column img {
  opacity: 0.8;
  cursor: pointer;
}

img {
  width: 100%;
  height: auto;
}

.column img:hover {
  opacity: 1;
}


/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}


/* The expanding image container (positioning is needed to position the close button and the text) */

.container {
  position: relative;
  display: none;
}


/* Expanding image text */

#imgtext {
  position: absolute;
  bottom: 15px;
  left: 15px;
  color: white;
  font-size: 20px;
}


/* Closable button inside the image */

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="main.css">
</head>

<body>
  <!-- The grid: four columns -->
  <div class="row">
    <div class="column">
      <img src="img/img_nature.jpg" alt="Nature" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="img/img_snow.jpg" alt="Snow" onclick="myFunction('img/img_lights.jpg');">
    </div>
    <div class="column">
      <img src="img/img_mountains.jpg" alt="Mountains" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="img/img_lights.jpg" alt="Lights" onclick="myFunction(this);">
    </div>
  </div>

  <!-- The expanding image container -->
  <div class="container">
    <!-- Close the image -->
    <span onclick="closeExpandedImg(this);" class="closebtn">&times;</span>

    <!-- Expanded image -->
    <img id="expandedImg">

    <!-- Image text -->
    <div id="imgtext"></div>
  </div>

  <script src="script.js"></script>
</body>

</html>

Sequences and JavaScript

I try coding this sequence:

M(0) = 1,
M(1) = 1, 
M(2) = 1, 
M(2t) = M(t) + M(t + 1) + t (for t > 1), 
M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)

my attempt was (but still wrong):

function seq(num)
{
    var num1=1;
    var num2=1;var num3=2
    var sum1;var sum2;
    var i=0;                                                             
    if (num>=1){                                                            
      for (i = 0; i < num; i++) {                           
        sum2=num1+num2+1;
        num1=num2;
        num2=sum2; } }                                                          
    if (num>1){
        for (i = 0; i < num; i++)
        {
        sum1=num1+num2+num;
        num1=num2;
        num2=sum1;
       }}
    return num2;
}

document.write("seq(1): "+seq(1)+"<br>");```

Prisma findmany() gives me a server error?

I was testing my new implemented prisma/postgresql database, but while searching for specific keywords, I got this error :

“Error:
Invalid prisma.easytokens.findMany() invocation:

Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: “ERROR”, parsed_severity: Some(Error), code: SqlState(E42601), message: “syntax error in tsquery: “Luna Rush””, detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some(“tsquery.c”), line: Some(692), routine: Some(“makepol”) }) }) })”

I have checked if the database is correctly connected to prisma & if the prisma client is intsalled, but all good.

Any suggestions?

Models :

<!-- begin snippet: js hide: false console: false babel: false -->

<!-- language: lang-js -->

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["fullTextSearch"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Token {
  id Int @id @default(autoincrement()) 
  tokenName String @db.VarChar(255)
  whitelistWallets String[] @db.VarChar(255)
  tokenAddress String @db.VarChar(255)
  coingecko String @db.VarChar(255)
  month String[] @db.VarChar(255)
  m1 String[] @db.VarChar(255)
  m2 String[] @db.VarChar(255)
  m3 String[] @db.VarChar(255)
  m4 String[] @db.VarChar(255)
  m5 String[] @db.VarChar(255)
  m6 String[] @db.VarChar(255)
  m7 String[] @db.VarChar(255)
  m8 String[] @db.VarChar(255)
  m9 String[] @db.VarChar(255)
  m10 String[] @db.VarChar(255)
  m11 String[] @db.VarChar(255)
  m12 String[] @db.VarChar(255)
  m13 String[] @db.VarChar(255)
  m14 String[] @db.VarChar(255)
  m15 String[] @db.VarChar(255)
  tge String[] @db.VarChar(255)
}

model easytokens {
  id Int @id @default(autoincrement()) 
  tokenName String @db.VarChar(255)
  whitelistWallets String[] @db.VarChar(255)
  tokenAddress String @db.VarChar(255)
  coingecko String @db.VarChar(255)
  month String[] @db.VarChar(255)
  m1 String[] @db.VarChar(255)
  m2 String[] @db.VarChar(255)
  m3 String[] @db.VarChar(255)
  m4 String[] @db.VarChar(255)
  m5 String[] @db.VarChar(255)
  m6 String[] @db.VarChar(255)
  m7 String[] @db.VarChar(255)
  m8 String[] @db.VarChar(255)
  m9 String[] @db.VarChar(255)
  m10 String[] @db.VarChar(255)
  m11 String[] @db.VarChar(255)
  m12 String[] @db.VarChar(255)
  m13 String[] @db.VarChar(255)
  m14 String[] @db.VarChar(255)
  m15 String[] @db.VarChar(255)
  tge String[] @db.VarChar(255)
}

Search function :

import { PrismaClient } from '@prisma/client'
import Head from 'next/head'
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { useContext } from 'react';
import Prismafilter from './prismafilter';

const prisma = new PrismaClient()


export default function Kek(props) {

    const {data} = props.result;

    console.log(data)

}

export async function getServerSideProps(context) {

    const result = await prisma.easytokens.findMany({
        where: {
          tokenName: {
            search: 'Luna Rush',
          },
        },
      })

    return {
      props: {
        
        result,
    
    }, // will be passed to the page component as props
    }
  }

How I can resolve this problem with jQuery?

I’m building a little e-commerce and I have the following problems:when I re-click on the button “next” the function will not called and when I click on previous button the function will not called.Here it is the code

var current_fs, next_fs, previous_fs; //fieldsets
    var left, opacity, scale; //proprietà dei fieldset che andremo ad animare
    var animating; //flag per evitare dei click troppo veloci

    $(".next").click(function () {
      if (animating) return false;
      animating = true;

      //assegno i fieldset "attuale" e "successivo" accedendo al tag "padre" di entrambi i pulsanti
      current_fs = $(this).parent();
      next_fs = $(this).parent().next();
        
      if(current_fs.is("#firstField")){
          console.log("first");
         if(checkFirstField()){
             animationNext(current_fs,next_fs);
         }
      }if(current_fs.is("#secondField")){
          console.log("second");
          if(checkSecondField()){
              
          }
      }
      
    })

javascript How to set destructuring values?

I have this:

  const { 
    user,
    id,
    name,
    desc,
    photos,
    video,
    price,
  } = route.params;

  <ProductFooter 
    selectedOptions={selectedOptions}
    {...route.params}
  />

Now I want to get the user in a variable and the other props in another variable

const ProductFooter = ({...props}) => {
  const { t } = useTranslation();
  const dispatch = useDispatch();

  const user = the user props,
  const product = the other props

How can I set now the values ?

Select even and odd words from a sentence given in a prompt window

I’m Educating myself in high school to become a developper and i got an assignment where i need some help:

Write the evenOdd() function. Ask, via a prompt window, a random sentence of at least five words to the visitors of the web page.
If the entered sentence consists of less than five words, visitors should see an error message in an alert window.
If the entered sentence consists of more than five words, the sentence must be adapted by the script. The script must ensure that every odd word starts and ends with a capital letter. The letters of the even words and the intermediate letters of the odd words (if they exist) must be in lowercase. The sentence is afterwards shown in an alert window.

How to convert a method to recursive function in Javascript?

I created a submenu from the first keys of the “res” data before the dot. In this submenu, I showed the keys with the same name in the “res” data only once. ie: “user”, “department” and “project” appear as just a submenu item. But when I click on them, other keys with the same name do not appear once. For example: When I click on the “project” item, 5 “type” submenus are opened. And I need to do the same for the “id” key, too. How can I solve this?

var res = {
    "user": "user1",
    "user.name": "username",
    "user.name.firstname": "firstname",
    "user.name.lastname": "lastname",
    "department": "dep",
    "department.id": "123",
    "project.name": "project",
    "project.type.name": "project1",
    "project.type.id": "321456789",
    "project.type.id.first3": "321",
    "project.type.id.last3" : "789",
    "project.type.id.abc": "abc",

}
var myList = []
var myFinalList = []

Object.keys(res).forEach(key => {
    var subMenus = key.split(".")
    subMenus.forEach(subMenu => {
        var newObject = {}
        newObject["id"] = subMenu
        newObject["content"] = subMenu

        myList.push(newObject)
    })
    for (var i = myList.length - 1; i >= 0; i--) {
        if (i - 1 !== -1) {
            //console.log(i - 1)
            myList[i - 1]["submenu"] = [myList[i]]
        }
    }
    myFinalList.push(myList[0])
    //console.log(myList)
    myList = []
})
var mySet = new Set()
myFinalList.forEach(obj => {
    mySet.add(obj["id"])
})
    var veryFinalList = []
    mySet.forEach(key => {
        var eachKeyObject = myFinalList.filter(sub => sub.id === key)

        var sourceObject = eachKeyObject[0]
        if(eachKeyObject.length > 1){
            for(var i = 1; i < eachKeyObject.length; i++){
                sourceObject["submenu"] = sourceObject["submenu"].concat(eachKeyObject[i]["submenu"])
            }
        }
        veryFinalList.push(sourceObject)
        console.log(veryFinalList)
    })

Using sp.js functions outside of sharepoint

I’m trying to get the users information name and Email from sharepoint using their JS library. I have managed to do so however, i have the home page for this website on a local server running an Apache web server due to my need for PHP (For MySql Database Query). I thought about passing the information through the URL but the realisation that the homepage is linked on every single page 1000+ pages and having to add this to every page would be daunting, primarily because of Sharepoints horrid upload system. I will list the code that i used on the sharepoint site.

Script Tags:

    <script src="/_layouts/15/init.js"></script>
    <script src="/_layouts/15/MicrosoftAjax.js"></script>
    <script src="/_layouts/15/ScriptResx.ashx?name=sp.res&culture=en-us"></script>
    <script src="/_layouts/15/sp.runtime.js"></script>
    <script src="/_layouts/15/SP.Core.js"></script>
    <script src="/_layouts/15/sp.js"></script>    

JS Code:

<script type="text/javascript">  
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');  
var currentUser;  
function init()
{  
    this.clientContext = new SP.ClientContext.get_current();  
    this.oWeb = clientContext.get_web();  
    currentUser = this.oWeb.get_currentUser();  
    this.clientContext.load(currentUser);  
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));  
}  
  
function onQuerySucceeded() 
{
    var username = currentUser.get_title(); 
    var useremail = currentUser.get_email(); 

    if (typeof(Storage) !== "undefined")
    {
        localStorage.setItem("userName", username);
        localStorage.setItem("email", useremail);
        document.getElementById("userTitle").innerHTML = username;
        document.getElementById("userEmail").innerHTML = useremail;
        var urlString = "URL Censored?username=" + username + "&email=" + useremail;
        window.location = (urlString);
    }   
}  
  
function onQueryFailed(sender, args) 
{  
    alert('Request failed. nError: ' + args.get_message() + 'nStackTrace: ' + args.get_stackTrace());  
}  

HTML Display Code:

<div class="information">
        <span id="userTitle"></span></br>  
        <span id="userEmail"></span></br>  
    </div> 

CSS:

.information
{
    position: absolute;
    top: 10px;
    right: 10px;
    color: white;
}

I will not claim this JavaScript as my own. I am primarily a Java dev. I’ve only started making this website recently. (4 Months or so) Any help understanding this would be much appreciated. Putting forth alot of effort to learn this in hopes of being where i am in Java at one point.