How to wait for multiple API calls to reutrn?

I have an array of APIs to query. For example var urls = ['example.org?x=1', 'example.org?x=2,3'] How can I have ReactJS wait for all the responses to come back before responding to the client?

I’ve tried a modification @Shanoor’s answer from Promises with http.get node.js but the result to the client is empty ("").

var http = require('http');
var urls = ['example.org', 'example2.org', '...'];

var done = 0;
var result = [];

function callback(index, data) {
  result[index] = data;
  done++;
  if (done == urls.length) {
    result.forEach(console.log);
    //I tried using the resp object here to return result[] but the data seemed corrupt 
  }
}

function processUrl(url, index) {
  var finalData = '';
  http.get(url, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(data) {
      finalData += data;
    });
    response.on('error', console.error);
    response.on('end', function() {
      callback(index, finalData);
    })
  });
}

app.get("/api/blah", (resp) => {
  urls.forEach(processUrl);
  //resp(result); this would result in an empty response
}

How to Delete Image from Firebase cloud Storage – REACT

I have the following structure in my Storage, Post/ID/image.jpg . Post and ID are folders that can be found easily but ID may contain multiple images. How could I possibly delete all of them ?
Inside my code, I have a function that should delete Posts inside firestore database and delete the images reference from the firebase storage

The error thrown is :

TypeError: Cannot read properties of undefined (reading ‘_throwIfRoot’)

Delete Function

const DeletePost = async (e) => {
    e.preventDefault();
    const querySnapshot = await getDocs(collection(db, `${category}Posts`));
    querySnapshot.forEach((docx) => {
        if (post.AdTitle === docx.data().AdTitle) {
            try {
                deleteObject(ref(storage, `${category}Posts`, docx.id).child);
                deleteDoc(doc(db, `${category}Posts`, docx.id));
            } catch (error) {
                console.log("error in delete image, " + error);
            }
            // router.reload();
        }
    });
};

discord.js Can’t add a role to member

I wan’t my bot to give a certain role to people when they join the server. But I get some weird error I don’t really understand.
This is the code

const { GuildMember, MessageEmbed } = require("discord.js");

module.exports = {
    name: "guildMemberAdd",
    /**
     * @param {GuildMember} member
     */
    async execute(member){
        let role = member.guild.roles.cache.some(role => role.name === 'Member')
        member.roles.add(role)

        member.guild.channels.cache.get(process.env.WELCOME_MESSAGE_CHANNEL_ID).send({ 
            embeds: [
                new MessageEmbed()
                .setTitle("Welcome! :smiley:")
                .setDescription(`${member.toString()} has joined the server!n
                                Thanks for joining. Head over to <#${process.env.RULE_CHANNEL_ID}> and verify yourself in <#${process.env.VERIFY_CHANNEL_ID}> to get access to all other channels.`)
                .setThumbnail(member.user.displayAvatarURL())
                .setColor("GREEN")
            ]
        }) 
    }
}

And after someone joins I get this error message
TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.

Return function failing to return in catch function using Discord.JS

I’m working on a react command to make the bot react to the given message ID, but the problem is that it works fine if it’s an emoji, but if it’s not an emoji, it says Please use a valid emoji! and then says Reacted with (emoji), despite the fact that I made the catch function return after saying Please use a valid emoji!, so I’m pretty confused, is there any way around it?

The code:

const { MessageEmbed } = require('discord.js')

module.exports = {
    name: 'react',
    category: 'Staff',
    aliases: [],
    description: 'Reacts to a message.',
    usage: 'react <messageID> <emoji>',
    userperms: [],
    botperms: [],
    run: async (client, message, args) => {
    if (message.author.bot) return;

    let emoji = args[1];
    let messageID = args[0];

    if (!messageID) return message.reply('Please state the messageID!')
    if (!emoji) return message.reply('Please state the emoji')

  if (messageID && emoji) {

    message.channel.messages.fetch(messageID)
      .catch(err => {
        if (err.code === 10008){
            message.channel.send('I cannot find this message!');
            return;
        }
        if (err.code === 50035){
            message.channel.send('Please state a valid Message ID!');
            return;
        }
      });
      message.channel.messages.fetch(messageID)
      .then(msg => {
        msg.react(emoji)
        .catch(() => {
          message.channel.send('Please use a valid emoji!')
          return
        })
        setTimeout(function(){
          message.channel.send('Please wait...').then(m =>
            setTimeout(function(){
              m.edit('Reacted with ' + emoji)
              return
            }, 1500)
          )
        }, 2000)
      })
    }
  }
}

Thanks 😀

javascrupt- ho do i check diagonal win in TIC Tac Toe?

i created a Tic Tac Toe game on javascript and HTML. in the game the user can choose on how many columes and rows he wants to play. i was abble to check win in a row and a colum but i don’t have any idea for a diagonal. I need to make it as simple as posible, and i will be very thenkfull if someone can help.
here is the javascript code:

var rows;
var cols;
var Array;
var tor = 0;
function XO() {
    rows = +prompt("Enter rows : ");
    cols = +prompt("Enter cols : ");

    intBoard = new Array(rows);
    var r, c;
    for (r = 0; r < intBoard.length; r++) {
        intBoard[r] = new Array(cols);
        for (c = 0; c < cols; c++) {
            intBoard[r][c] = 0;
        }
    }

    var idNum = 0;
    var strToShow = "<table border='1'>";
    for (var r = 0; r < rows; r++) {
        strToShow = strToShow + "<tr>";
        for (var c = 0; c < cols; c++) {
            strToShow = strToShow + "<td id='" + idNum.toString() +
                " ' onclick='TdClicked(this)' width='80px' height='80px' >";
            //strToShow = strToShow + idNum.toString();
            strToShow = strToShow + "<img src='background.jpg' width='80px' height='80px' />";
            strToShow = strToShow + "</td>";
            idNum++;
        }
        strToShow = strToShow + "</tr>";
    }
    strToShow = strToShow + "</table>";
    document.write(strToShow);
}


var showfirst = 0;
function TdClicked(tdClickedThis) {
    var idClicked = tdClickedThis.id;
    var rowClicked = Math.floor(idClicked / cols);
    var colClicked = idClicked % cols;

    if (showfirst == 0) {
        document.getElementById(idClicked).innerHTML = "<img width='80px' height='80px' src='wolf.jpg'/>";
        showfirst++;
        intBoard[rowClicked][colClicked] = 1;

        for (c = 0; c < cols; c++) {           // check win in column
            if (intBoard[rowClicked][c] != 1)
                c = cols + 111;   //break;
        }
        if (c == cols)
            alert("PLAYER X WIN!!")


        for (r = 0; r < rows; r++) {           // check win in row
            if (intBoard[r][colClicked] != 1)
                r = rows + 111;   //break;
        }
        if (r == rows)
            alert("PLAYER X WIN!!")


        
    }

    else {
        document.getElementById(idClicked).innerHTML = "<img width='80px' height='80px' src='fox.png'/>";
        showfirst--;
        intBoard[rowClicked][colClicked] = 2;

        for (c = 0; c < cols; c++) {            //check win in column
            if (intBoard[rowClicked][c] != 2)
                c = cols + 111;   //break;
        }
        if (c == cols)
            alert("PLAYER O WIN!!")


        for (r = 0; r < rows; r++) {            // check win in row
            if (intBoard[r][colClicked] != 2)
                r = rows + 111;   //break;
        }
        if (r == rows)
            alert("PLAYER O WIN!!")

    }
}

connect a servise worker to a contect script

In short, I want that when you press my extension button from the context menu, the content script (contect-script) will be added to the web page temporarily. I tried to use sendMessage() but it just didn’t work.

Any help will be appreciated:)

//This is the servise worker (eventPage)

chrome.runtime.onInstalled.addListener(() => {
 chrome.contextMenus.create({
   id: 'select',
   title: 'select',
   type: 'normal',
   contexts: ['all']
 });

})
chrome.contextMenus.onClicked.addListener(function (clickDate) {
 if (clickDate.menuItemId == 'select') {
   //send massege to make content-script start operate
  chrome.runtime.sendMessage('start');

 }
});



-------------------------------------------------------------------------


//lets say that this is the content-script
chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){

if(response == 'start'){

// js code that is inserted into the site
}
});
{
"manifest_version": 3,

"name": "SendFast",
"description": "This extension makes it easier to send information",
"version": "1.0",
"icons": {
  "128": "16-nahum.png",
  "48": "64-nahum.png",
  "16": "16-nahum.png"
},

"action": {
  "default_icon": "16-nahum.png",
  "default_popup": "popup.html"
},
"permissions":["contextMenus","activeTab"],


"background":{
  "service_worker": "eventPage.js"
},
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content-script.js"]
  }
]

}

is the any function that converts to lowerCase and at the same time Capitalizes the first chars in the given strings? [closed]

Hello! all Engineers and programmers! There should be a function to make all characters in a given line of string or even list convert to lowerCase and at the same time Capitalize the first chars in the given strings. I found it very useful and have used my own functions in a variety of places such as search and delete, functions, where the user might write the wrong spelling name, mixed capitalized and lowercase.

Why there is not a built-in function that converts to lowerCase and at the same time Capitalizes the first chars in the given strings and removes punctuations?

I know how to solve it, However, I think there should be a generalized algorithm for this implication. Since we use it frequently, Don’t you agree?

If you know any, please share with us here! for future users!

Thanks!

change day by clicking on buttom

i want each time that im clickig on button that show me the Next day from day array list , can some one help me ?( the only way that i could get a answer is Math.random() to have difference result each time i am clicking on button , but i want that show me the next day each time i am clicking on it .


<button onclick='day()'>Click to see</button>
<script>
    function day(){
       var days =['Monday','Thuesady','Wensday','Thursday','Friday','Saturday','Sunday']
        document.getElementById("demo").innerHTML = days[Math.floor(Math.random() *7)];} 
        
    }
</script>

CSS Grid spacing increases on click

I am using a grid display for the body, and in one of my grid template containers, I have a nested grid template to organize my projects. however, whenever I click on a project and it expands it doubles the spacing between the body grid container elements causing the website to double in length.

body{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
    grid-template-areas: 
    "text text text"
    ". picture ."
    "text text text "
    ". resume . "
    "text text text "
    "projects projects projects"
    "text  text text "
    ". text  ."
    ;
    

}

.projects{
    grid-area: projects;    
    align-items: center;
    display: grid;
    grid-template-columns: 2fr 2fr 2fr;
    grid-template-rows: 2fr 2fr 2fr;
    grid-template-areas:
    "project project project"
}   

Here is the Javascript Function to open the project

function openproject(){
    var text = document.getElementById("project") 
    var project = document.getElementById("project")
    var project2 = document.getElementById("project 2")
    if (text.style.display=="none"){
        text.style.display ="inline"
        project.style.backgroundColor = "hsl(49 37% 94%)"
        project.style.color ="var(--bg-color)"
        project2.style.display ="none" 
         
    }else{
        text.style.display ="none" 
        project.style.textDecoration="none"
        project.style.backgroundColor="var(--bg-color)"
        project.style.color="hsl(49 37% 94%)"
        project2.style.display ="inline" 
        
    }
}

and the HTML is essentially just variations of this

 <div class="projects">
        <div class="project" id="project" onclick="openproject()">
          Project Name! 
          <span id="projectText" class="projectText" style="display: none">
            <p>
              Text
            </p>
            <a
              href=link
              target="_blank"
              style="text-decoration: none; color: var(--bg-color)"
            >
              <strong> Check Out the Project! </strong>
            </a>
          </span>
        </div>

Thank You in advance!

Javascript, maximun call stack size exceeded

I was writing some code for a widget in “Scriptable” that shows random word at a certain time. The widget calls itself with a timeout, on iPad. But it’s exceeding the stack size. How do I solve this? I am using Javascript within “Scriptable” framework, so I don’t have much freedom.

kanjiObj: Object; kanjiKeys: List; Timer().schedule(timeinterval, repeat, callback)

var randomNum = Math.floor(Math.random()*150)+1
var kanji = kanjiKeys[randomNum]
var kanjiMeaning = kanjiObj[kanjiKeys[randomNum]]

if(config.runsInWidget){
  let widget = createWidget()
  Script.setWidget(widget)
  Script.complete()
  
function createWidget(){
  let widget = new ListWidget()
  widget.addText(kanji + "=>" + kanjiMeaning)
  widget.wait = new Timer().schedule(1000*60*60, 150, createWidget())

Navigation .a and help understand

Need help understanding if what my wicked mind has stumbled across and what thought I put back into universe has done any justice for my keenly thought out plan? Navigation is needed to assure my Renaissance..a

how to run this code using phantomjscloud

this e Node js script is a web crawler using puppeteer + a rotating IP using proxyrack but I need to run this code in phantomjscloud I need each browser to have its own IP address, how can I do that ??
this e Node js script is a web crawler using puppeteer + a rotating IP using proxyrack but I need to run this code in phantomjscloud I need each browser to have its own IP address, how can I do that ??

const puppeteer = require('puppeteer');
const langBtns = require('./langBtns');
const proxy = require('./proxy');
const { promisify } = require('util');
const sleep = promisify(setTimeout);
const devices = Object.values(puppeteer.devices);       //Set of mobile devices provided by puppeteer

//Array of all objects found in the langBtns.JSON file
let choices = Object.values(langBtns);
let goodBtnSelector;
let windows = 1000000;       //The total number of windows to be opened throughout the execution of the code
let concurrency = 10;    /* The number of windows running concurrently.
                           This variable acts like a semaphore, whenever a window is running, it is decremented;
                           and whenever a window finishes execution, it is incremented to allow more windows to open */
let flags = [];
flags.fill(true);

let startTime;
let endTime;
let elapsedTime;
let counter = 0;

class BrowserHandler{
    constructor(index) {
        const launch_browser = async () => {
            this.index = index;
            this.browser = false;
            this.browser = await puppeteer.launch({
                headless: false,
                slowMo: 10,
                executablePath:
                "C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
                args: [
                    `--proxy-server=${proxy.proxyProvider}`,
                    "--no-sandbox",
                    "--disable-setuid-sandbox",
                    "--disable-dev-shm-usage",
                    "--disable-accelerated-2d-canvas",
                    "--no-first-run",
                    "--no-zygote",
                    "--disable-gpu",
                    "--disable-notifications"]
            });
            this.browser.on('disconnected', async() => {
                if(this.status === 0){
                    console.log("Browser ", this.index, " disconnected.");
                    concurrency++;
                    doStuff(index).catch(e => {
                        console.log('Error happened, Oops: ', e);
                    });
                }
            });
        };
        (async () => {
            await launch_browser();
            console.log("Browser", this.index, "connected.");
        })();
    }
    setStatus(status){
        this.status = status;
    }
}

const wait_for_browser = browser_handler => new Promise((resolve, reject) => {
    const browser_check = setInterval(() => {
        if (browser_handler.browser !== false) {
            clearInterval(browser_check);
            resolve(true);
        }
    }, 100 );
});



async function start(){
    startTime = performance.now();
    for (let i = 0; i < windows; i++) {
        if(concurrency !== 0){
            doStuff(i).catch(e => {
                console.log('Error happened, Oops: ', e);

            });
        }
        while(concurrency === 0) {
            await sleep(100);
        }
    }
}

start();

async function checkCounter() {
    if (counter === windows) {
        endTime = performance.now();
        elapsedTime = (endTime - startTime)*0.001;  //To seconds
        if(elapsedTime < 60){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2), " seconds");
        }else if(elapsedTime < 3600){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2) / 60, " minutes");
        }else{
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(3) / 3600, " hours");
        }
        process.exit();
    }
}

async function doStuff(index) {
    concurrency--;
    const browser_handler = new BrowserHandler(index);
    await browser_handler.setStatus(0);
    await wait_for_browser(browser_handler);
    const [page] = await browser_handler.browser.pages();
    await page.setDefaultNavigationTimeout(0);
    const randInt = Math.floor(Math.random() * 25001);
    if(randInt % 2 === 0){      //Choose mobile
        const device = devices[Math.floor(Math.random() * devices.length)];
        console.log("");
        console.log("Browser ", index, " Device: " , device.name);
        await page.emulate(device);
    }
    else{
        console.log("Browser ", index, " Device: Desktop");
    }
    try{
        await page.authenticate({
            username: proxy.username,
            password: proxy.password,
        }).then(async () => {
            let randObj = choices[Math.floor(Math.random() * choices.length)];
            let lang = randObj.language;
            goodBtnSelector = randObj.goodButtonSelector;
            await page.goto(`https://coinmarketcap.com/${lang}/`, {"waitUntil":["load", "networkidle2"], timeout: 60000})
                .then(async () => {
                    try {
                        {
                            const frame = page.mainFrame();
                            const promise = page.waitForNavigation();
                            const element = await frame.waitForSelector(".dQjfsE");
                            await element.click();
                            const element2 = await page.waitForSelector(".bzyaeu-3", {timeout: 5000});
                            await element2.type("Tiger22" , {timeout: 5000});
                            await element2.press('Enter' , {timeout: 5000});
                            await promise;
                        }
                        {
                            const frame = page.mainFrame();
                            await autoScroll(page);
                            const element = await page.waitForSelector(goodBtnSelector);
                            await page.waitForTimeout(2000);
                            await element.click();
                            await page.waitForTimeout(5000);
                            await autoScrollUp(page);
                            console.log("     Browser ", index, "Done ");
                            await browser_handler.setStatus(1);
                            await browser_handler.browser.close();
                            concurrency++;
                            counter++;
                            checkCounter();
                        }
                    }catch(e){
                        browser_handler.status = 0;
                        browser_handler.index = index;
                        await browser_handler.browser.close();
                    }
                })
        })
    }catch(e){
        browser_handler.status = 0;
        browser_handler.index = index;
        await browser_handler.browser.close();
    }
}

async function autoScroll(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

async function autoScrollUp(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, -distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}



const puppeteer = require('puppeteer');
const langBtns = require('./langBtns');
const proxy = require('./proxy');
const { promisify } = require('util');
const sleep = promisify(setTimeout);
const devices = Object.values(puppeteer.devices);       //Set of mobile devices provided by puppeteer

//Array of all objects found in the langBtns.JSON file
let choices = Object.values(langBtns);
let goodBtnSelector;
let windows = 1000000;       //The total number of windows to be opened throughout the execution of the code
let concurrency = 10;    /* The number of windows running concurrently.
                           This variable acts like a semaphore, whenever a window is running, it is decremented;
                           and whenever a window finishes execution, it is incremented to allow more windows to open */
let flags = [];
flags.fill(true);

let startTime;
let endTime;
let elapsedTime;
let counter = 0;

class BrowserHandler{
    constructor(index) {
        const launch_browser = async () => {
            this.index = index;
            this.browser = false;
            this.browser = await puppeteer.launch({
                headless: false,
                slowMo: 10,
                executablePath:
                "C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
                args: [
                    `--proxy-server=${proxy.proxyProvider}`,
                    "--no-sandbox",
                    "--disable-setuid-sandbox",
                    "--disable-dev-shm-usage",
                    "--disable-accelerated-2d-canvas",
                    "--no-first-run",
                    "--no-zygote",
                    "--disable-gpu",
                    "--disable-notifications"]
            });
            this.browser.on('disconnected', async() => {
                if(this.status === 0){
                    console.log("Browser ", this.index, " disconnected.");
                    concurrency++;
                    doStuff(index).catch(e => {
                        console.log('Error happened, Oops: ', e);
                    });
                }
            });
        };
        (async () => {
            await launch_browser();
            console.log("Browser", this.index, "connected.");
        })();
    }
    setStatus(status){
        this.status = status;
    }
}

const wait_for_browser = browser_handler => new Promise((resolve, reject) => {
    const browser_check = setInterval(() => {
        if (browser_handler.browser !== false) {
            clearInterval(browser_check);
            resolve(true);
        }
    }, 100 );
});



async function start(){
    startTime = performance.now();
    for (let i = 0; i < windows; i++) {
        if(concurrency !== 0){
            doStuff(i).catch(e => {
                console.log('Error happened, Oops: ', e);

            });
        }
        while(concurrency === 0) {
            await sleep(100);
        }
    }
}

start();

async function checkCounter() {
    if (counter === windows) {
        endTime = performance.now();
        elapsedTime = (endTime - startTime)*0.001;  //To seconds
        if(elapsedTime < 60){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2), " seconds");
        }else if(elapsedTime < 3600){
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(2) / 60, " minutes");
        }else{
            console.log(counter, " Windows Done in: ", elapsedTime.toPrecision(3) / 3600, " hours");
        }
        process.exit();
    }
}

async function doStuff(index) {
    concurrency--;
    const browser_handler = new BrowserHandler(index);
    await browser_handler.setStatus(0);
    await wait_for_browser(browser_handler);
    const [page] = await browser_handler.browser.pages();
    await page.setDefaultNavigationTimeout(0);
    const randInt = Math.floor(Math.random() * 25001);
    if(randInt % 2 === 0){      //Choose mobile
        const device = devices[Math.floor(Math.random() * devices.length)];
        console.log("");
        console.log("Browser ", index, " Device: " , device.name);
        await page.emulate(device);
    }
    else{
        console.log("Browser ", index, " Device: Desktop");
    }
    try{
        await page.authenticate({
            username: proxy.username,
            password: proxy.password,
        }).then(async () => {
            let randObj = choices[Math.floor(Math.random() * choices.length)];
            let lang = randObj.language;
            goodBtnSelector = randObj.goodButtonSelector;
            await page.goto(`https://coinmarketcap.com/${lang}/`, {"waitUntil":["load", "networkidle2"], timeout: 60000})
                .then(async () => {
                    try {
                        {
                            const frame = page.mainFrame();
                            const promise = page.waitForNavigation();
                            const element = await frame.waitForSelector(".dQjfsE");
                            await element.click();
                            const element2 = await page.waitForSelector(".bzyaeu-3", {timeout: 5000});
                            await element2.type("Tiger22" , {timeout: 5000});
                            await element2.press('Enter' , {timeout: 5000});
                            await promise;
                        }
                        {
                            const frame = page.mainFrame();
                            await autoScroll(page);
                            const element = await page.waitForSelector(goodBtnSelector);
                            await page.waitForTimeout(2000);
                            await element.click();
                            await page.waitForTimeout(5000);
                            await autoScrollUp(page);
                            console.log("     Browser ", index, "Done ");
                            await browser_handler.setStatus(1);
                            await browser_handler.browser.close();
                            concurrency++;
                            counter++;
                            checkCounter();
                        }
                    }catch(e){
                        browser_handler.status = 0;
                        browser_handler.index = index;
                        await browser_handler.browser.close();
                    }
                })
        })
    }catch(e){
        browser_handler.status = 0;
        browser_handler.index = index;
        await browser_handler.browser.close();
    }
}

async function autoScroll(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

async function autoScrollUp(page){
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, -distance);
                totalHeight += distance;

                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    });
}

Position of an element with Javascript for a suggest research box

I am trying to make a suggest research box like Google. I am not doing the server side with Ajax for the moment because I have a problem with my code. As you can see on the picture, the position of the suggestion box is not correct.

Positionement problem with JS

Here is the code :

  var values = ["Chatelet", "Gare de Lyon", "Orsay-Ville"];


function positionner() {
var suggest = document.getElementById("suggestion");
var champ = document.getElementById("fmsearch");
suggest.style.left = getLeft(champ) + "px";
suggest.style.top = (getTop(champ) + champ.offsetHeight) + "px";
}

function getLeft(element) {
var offsetLeft = 0;
while (element != null) {
offsetLeft += element.offsetLeft;
element = element.offsetParent;
}
return offsetLeft;
}
function getTop(element) {
var offsetTop = 0;
while (element != null) {
offsetTop += element.offsetTop;
element = element.offsetParent;
}
return offsetTop;
}
positionner();




function suggerer() 
{
  var suggest = document.getElementById("suggestion");
  suggest.innerHTML = "";
  var i, ele;
  for (i=0 ; i<values.length ; i++)
  {
    ele = document.createElement("div");
    ele.innerHTML = values[i];
    suggest.appendChild(ele);
  }
  suggest.style.display = "block";
}

Add filter view hyperlinks and rearrange the column values

I have Sheet1 with existing filter view hyperlinks. I want to find any names that dont have filterviews, then create filterviews with hyperlinks to these names and add them in alphabetical order to the list that already has hyperlinks.

Example:
In Sheet 1, Col C,E,G, new names: Tracy Jack,Maria Jose , Samuel Philips,Karan Tucker, Vincent Lee, Wes Lee do not have a filter view and hyperlink, I want to add filter view and hyperlink to these names and then add them alphabetically to the list of names with hyperlinks in the rows above

Before adding hyperlinks

After adding hyper link to

Tracy Jack (Col C),

Maria Jose , Samuel Philips (Col E),

Karan Tucker, Vincent Lee, Wes Lee(Col G),

I want to add insert these names with links in alphabetical order in the rows above. Please see pic below for final output

After adding and rearranging list