Shadowroot : Not getting the correct target for event listener

I have a webpage with a modal with a custom dropdown under a shadowroot as follows:

<div id="main">
#shadow-root
<div class="modal fade in" id="sample-modal">
    <div class="modal-dialog modal-xl" role="dialog" aria-hidden="true">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" style="font-size:0.85rem" id="download-modal-label">Modal Title</h6>
            </div>
            <form onsubmit="return false;">
                <div class="modal-body" id="modal-body" style="overflow: inherit !important">
                    <div class="dropdown">
                        <button onclick="myFunction()" class="dropbtn">Dropdown</button>
                        <div id="myDropdown" class="dropdown-content">
                        <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
                        <a href="#about">About</a>
                        <a href="#base">Base</a>
                        <a href="#blog">Blog</a>
                    </div>
                   </div>
                </div>
            </form>
        </div>
    </div>
</div>

For this, I want to add an event listener where if I click anywhere besides the dropdown, I hide the dropdown div. For this, I added the event listener as follows:

let root = document.getElementById("main").shadowRoot;
$(root).on("click", function(e) {
            var clickedOn=$(e.target);
        });

But this doesn’t seem to work at all. I tried attaching the click event listener to the document, to check the event target as follows:

$(document).on("click", function(e) {
            var clickedOn=$(e.target);
        });

This event listener is triggered, but the target element ‘e’ it shown as the <div id="main"> irrespective of if I click on any element including the dropdown element under the modal. How do I add the event listener where I get the correct element under the shadowRoot which was clicked on using the ‘click’ event listener?

fetch / response.text() messes up the utf-8

I am currently fetching(https://data.ssb.no/api/v0/dataset/49678.csv?lang=no) in javascript. I havent had any problem with fetching other sources so far but now I keep getting a issue with the decoding/encoding. When fetching in postman everything works fine and it returns the values “æøå”. However when I try to fetch this in node it gives a question mark where “æøå” is. I have a feeling something is off with the encoding however it prints fine in postman?

POSTMAN
0219 Bærum (-2019)";"0000 Alle husholdninger";"2005";"Inntekt etter skatt, median (kr)";411000
VSCODE:
"1621 �rland (-2017)";"0002 Par uten barn";"2020";"Inntekt etter skatt, median (kr)";.
async function FetchDataInntekt() {
  const url = "https://data.ssb.no/api/v0/dataset/49678.csv?lang=no";
  let dataresult = null
  const data = await fetch(url, {
    method: "GET",
    headers: { "Content-Type": "text/html; charset=UTF-8" }
  })
  console.log(data.body)
  let response = await data.text();
console.log(reponse)
}

The console.log(data.body)

<ref *1> Gunzip {
  _writeState: Uint32Array(2) [ 0, 0 ],
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    constructed: true,
    sync: false,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: null,
    closed: false,
    closeEmitted: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    dataEmitted: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {
    prefinish: [Function: prefinish],
    unpipe: [Function: onunpipe],
    error: [ [Function: onerror], [Function (anonymous)] ],
    close: [Function: bound onceWrapper] { listener: [Function: onclose] },
    finish: [Function: bound onceWrapper] { listener: [Function: onfinish] }
  },
  _eventsCount: 5,
  _maxListeners: undefined,
  _writableState: WritableState {
    objectMode: false,
    highWaterMark: 16384,
    finalCalled: false,
    needDrain: false,
    ending: false,
    ended: false,
    finished: false,
    destroyed: false,
    decodeStrings: true,
    defaultEncoding: 'utf8',
    length: 6406,
    writing: true,
    corked: 0,
    sync: false,
    bufferProcessing: false,
    onwrite: [Function: bound onwrite],
    writecb: [Function: nop],
    writelen: 6406,
    afterWriteTickInfo: null,
    buffered: [],
    bufferedIndex: 0,
    allBuffers: true,
    allNoop: true,
    pendingcb: 1,
    constructed: true,
    prefinished: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    errored: null,
    closed: false,
    closeEmitted: false,
    [Symbol(kOnFinished)]: []
  },
  allowHalfOpen: true,
  bytesWritten: 0,
  _handle: Zlib {
    onerror: [Function: zlibOnError],
    buffer: <Buffer 1f 8b 08 00 00 00 00 00 00 03 bc bd cd 8e a5 b9 91 a6 b9 9f ab 70 d4 4a 0d 54 cd 7c fc 27 7b 56 6a a0 0b d5 c0 74 4f 43 1a f4 3e 85 8c ca 4e 64 2a 53 ... 6356 more bytes>,
    cb: [Function (anonymous)],
    availOutBefore: 16384,
    availInBefore: 6406,
    inOff: 0,
    flushFlag: 2,
    [Symbol(owner_symbol)]: [Circular *1]
  },
  _outBuffer: <Buffer 22 72 65 67 69 6f 6e 22 3b 22 68 75 73 68 6f 6c 64 6e 69 6e 67 73 74 79 70 65 22 3b 22 e5 72 22 3b 22 73 74 61 74 69 73 74 69 6b 6b 76 61 72 69 61 62 ... 16334 more bytes>,
  _outOffset: 0,
  _chunkSize: 16384,
  _defaultFlushFlag: 2,
  _finishFlushFlag: 2,
  _defaultFullFlushFlag: 3,
  _info: undefined,
  _maxOutputLength: 4294967296,
  _level: -1,
  _strategy: 0,
  [Symbol(kCapture)]: false,
  [Symbol(kCallback)]: null,
  [Symbol(kError)]: null
}
```

What is the problem and why does it not return in utf8 like it does in postman and how can I encode/decode it to utf8? I have fetched from many other sites with no problem like this.

Object, swiperjs, destructure, array, map, filter, forEach

I have two question about my project.

  1. Today I put swiperJS in my project and when you try to click Book in some items my slider move and don’t open the modal. When you try to click on Fiesta Hotel, after loading the web, it doesn’t open the modal. This is my first time with SwiperJS and maybe someone has the same problem and can tell me what’s wrong.

  2. I make modal and do foreach on every book button, now i create the array of object, and wanna connect ModalBtns.id with cities.id how i can do?? I try map, filter and everything but still dont know how to connect this item because i wanna add info to modal dynamically. Like price for ticket and everything. I know in the future react it will be simply to use for operation like that, but i try do in JS

https://margsoftbf.github.io/trip-rest-website/

https://github.com/margsoftbf/trip-rest-website

Search accordion content for ID and open

I am using a basic accordion plugin where each item is added as a separate Gutenberg Block. The plugin does not allow me to add an ID to each block, only a class. When I try to add an ID within the Gutenberg code it returns the error ‘this block contains invalid content’- it’s also impractical for the clent.

While I don’t have control over the plugins ability to facilitate ID’s, the content in each panel is made up of ACF blocks where I can add ID’s.

I need to link to each panel from anchor links but this does not currently work as the ID’s reside within the collapsed accordion and so nothing happens.

Is there a way to search hidden content for a ID’s and then open its parent accordion panel?

This is how the accordion is structured by the plugin with an ACF map section as the content as an example

<div class=".aab__accordion_container">
   <div class=".aab__accordion_head">
      <div class=".aab__accordion_heading .aab_right_icon">
        <h4>the heading</h4>
      </div>
   </div>
   <div class=".aab__accordion_body">
      <section id="map-section">
         Content
      </section>
    </div>
</div>

An active accordion gets the class

.aab__accordion_body--show

added to

.aab__accordion_body

This switches between aria exanded: true or false on the accordion body and the CSS is:

.wp-block-aab-accordion-block .aab__accordion_body {
    display: block !important;
    position: absolute !important;
    top: -9999px !important;
    left: -9999px !important;
}

.wp-block-aab-accordion-block .aab__accordion_body.aab__accordion_body--show {
    position: relative !important;
    top: 0 !important;
    left: 0 !important;
}

I switched it to this css from the original ‘display none/block’ for screen readers and in hopes it would make the task easier but the page still just re-loads at the top with no effect.

To complicate things even more, these accordion panels also reside inside a Gutenberg group

The URL is here

http://staging.caledoniaworldwide.com/package/package-template-1

Thanks in advance

Google Map How to clear poligon and marker

I can not speak English well. Google Map How to clear poligon and marker? Help me please. I want poligon and market to be deleted when I click the button. I tried but I couldn’t.
Myscript :

function initMap() {

....
    function attachPolygonInfoWindow(polygon) {
        .....
    }
    google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
        $(".clear").removeClass("d-none");
        if (e.type == "polygon") {
            drawingManager.setOptions({
                drawingControl: false,
            });
            allOverlays.push(e);
            if (e.type != google.maps.drawing.OverlayType.MARKER) {
                drawingManager.setDrawingMode(null);
                var newShape = e.overlay;
                newShape.type = e.type;
                google.maps.event.addListener(newShape, "click", function() {
                    setSelection(newShape);
                });
                    var path = newShape.getPath();
                    google.maps.event.addListener(path, "insert_at", function() {
                        attachPolygonInfoWindow(newShape);
                    });
                    google.maps.event.addListener(path, "set_at", function() {
                        attachPolygonInfoWindow(newShape);
                        var data = "";
                        $.each(e.overlay.getPath().getArray(), function(key, latlng) {
                            var lat = latlng.lat();
                            var lon = latlng.lng();
                            data += lat + " - " + lon + "<br>";
                        });
                        $(".map_coordinat").html(map.getCenter().lat() + " - " + map.getCenter().lng());
                        $(".poligon_coordinat").html(data);
                    });
                    attachPolygonInfoWindow(newShape);
                }
                setSelection(newShape);
            }
        
    });
}

Can’t get other values to show using react

I can’t figure out how to get more values to show in my table using REACT. The only thing that I am able to show is the cost. I can’t show Manufacturer and Item. So When I choose Iphone12 – Manufacturer will be “Apple” and Item will be “iPhone 12” & Galaxy S21 will be “Android” and “Galaxy 21”,from the data structure in index.
This is my Index.js :

```import React from 'react';
import ReactDOM from 'react-dom';
import './Home.css';
import 'bootstrap/dist/css/bootstrap.min.css'
import MTWork  from "./MTWork";
let inventory = [
    { 'id': 0, 'manufact': 'None', 'item': 'None', 'descr': 'None', 'avail': 0, 'price': 0},
    { 'id': 100, 'manufact': 'Samsung', 'item': 'Galaxy S22', 'descr': 'The Lastest Phone', 'avail': 22, 'price': 1399.99 },
    { 'id': 101, 'manufact': 'Samsung', 'item': 'Galaxy S21', 'descr' : 'Recently refurbished like new', 'avail': 5, 'price': 699.99 },
    { 'id': 102, 'manufact': 'Samsung', 'item': 'Galaxy S20', 'descr' : 'Great phone works well', 'avail': 3, 'price': 399.99 },
    { 'id': 103, 'manufact': 'Apple', 'item': 'iPhone 13', 'descr' : 'New and Shiny, Nothing better', 'avail': 13, 'price': 1299.99 },
    { 'id': 104, 'manufact': 'Apple', 'item': 'iPhone 12', 'descr' : 'Refurbished but perfect', 'avail': 13, 'price': 899.99 },
    { 'id': 105, 'manufact': 'Apple', 'item': 'iPhone 11', 'descr' : 'Works great!', 'avail': 12, 'price': 599.99 }
];
let warranty = [
    { 'id': 0, 'plan' : 'None', 'cost' : 0  },
    { 'id': 1, 'plan' : 'Extended', 'cost' : .15  },
    { 'id': 2, 'plan' : 'Normal', 'cost' : .1  },
    { 'id': 3, 'plan' : 'Base', 'cost' : .05  }
];
let title = "Teds Technology Treasures"
ReactDOM.render(
    <React.StrictMode>
        <MTWork  title ={title} phones ={inventory} wrnty = {warranty} />
    </React.StrictMode>,
    document.getElementById('root')
);``` 

THIS IS MY MTWork.js -----------------------------------


```import {useState} from "react";


function MTWork(props){
    const {phones, title, wrnty} = props;


    const[name, setName] = useState("Kels");
    const[itm, setAndroid] = useState();
    const[Atem, setApple] = useState();
    const[Warrant, setWarranty] = useState(0);
    const[total, setTotal] = useState( 0);


    function updateName(n) {
        setName(n.target.value);
    }
    function updateAndroid(a){
        setAndroid(a.target.value);
    }
function updateApple(ap){
        setApple(ap.target.value);
    }
    function updateWarranty(w) {
        setWarranty(w.target.value);
    }

    function doOrder() {
        let total=0;
        let total2 = parseFloat(itm) + parseFloat(Atem);
       let wTotal = (total2)*(parseFloat(Warrant));
        total += total2+wTotal;
        return setTotal(total);

    }

    return(
        <div>
            <div className="container-fluid">
                <div className="row">
                    <div className="col">
                        <h1>  <span className='title'> {title}</span></h1>
                    </div>
                </div>
                <div className="row">
                    <div className="col-4">
                        Name: <input type='text' value={name}
                                     onChange = {updateName}/> <br/>
                       Android Phone: <select onChange={updateAndroid} value={itm} >
                        {phones.map( ( phn ) => (
                            <option key={phn.id} value={phn.price}> {phn.item} </option>
                        ))}
                    </select> <br/>
                        Apple Phone: <select onChange={updateApple} value={Atem} >
                        {phones.map( ( Apn ) => (
                            <option key={Apn.id} value={Apn.price} > {Apn.item} </option>
                        ))}
                    </select><br/>
                        Warranty: <select onChange={updateWarranty} value={Warrant} >
                        {wrnty.map( ( wrn ) => (
                            <option key={wrn.id} value={wrn.cost}> {wrn.plan} </option>
                        ))}

                    </select><br/>
                        <button className='btn btn-dark' onClick={ () => doOrder()}> Order</button>
                        <h2 style={{color:"blue"}}>Results For Name: {name}</h2>

                        <table className="table" >
                            <tbody className="color">
                            <tr><th>Manufacturer:</th><th>Item: </th><th>Cost: </th></tr>
                            <tr>
                                <td scope="row">{phones.maunfact}</td>
                                <td scope="row">{phones.price}</td>
                                <td scope="row">{itm}</td>
                            </tr>
                            <tr>
                                <td scope="row">{phones.manufact}</td>
                                <td scope="row">{phones.price}</td>
                                <td scope="row">{Atem}</td>
                            </tr>
                            <tr>
                                <td> Warranty</td>
                                <td scope="row">{props.plan}</td>
                                <td scope="row">{Warrant}%</td>
                            </tr>
                            <tr>
                                <td scope="row">Total </td>
                                <td scope="row"> </td>
                                <td scope="row">{total} </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    )

}export default MTWork;```

[This is how the final product should look like in the end.)[1]
[1]: https://i.stack.imgur.com/mxBOK.png

search suggestion based on any letter of string

i am trying to write some java script code the auto suggest based on pretrial strings so to speak

here an example of what i mean:

if we have array of strings =>
[ ‘text’ , ‘apple’ , ‘texas’ , ‘time’ , ‘java’ , ‘java script’ , ‘pen’ ]

what i want to achieve is this :
when the user type ==> “te” the function should return this ==> ‘text’ and ‘texas’

BUT

if user type ==> “t*e” OR “t e” with space between the function should return this
==> ‘text’ , ‘texas’ , AND ‘time’ since it contains the tow letters no matter the oreder

the same if user type ==> “p*e” OR “p e” the result should be ==> ‘apple’ and ‘pen’
since booth contain the letters ‘p’ and ‘e’

here what i have done so far

const nameInput = document.getElementById('name')

const names = [ 'text' , 'apple' , 'texas' , 'time' , 'java' , 'java script' , 'pen' ]

nameInput.addEventListener('keyup', ()=> {
  // console.log(nameInput.value)
const text = nameInput.value.trim().replace(/s/g, '')
// console.log(text)
const a = names.filter(name => name.includes(text))
console.log(a)
})
<input type="text" placeholder="search"  id="name">

“Cannot read” error when trying to access Object’s properties

I have this JS Object that contains 3 “thread” objects each with different values.
I am trying to get the values from each of the threads. I am able to print the entire json object, but I can’t print individual values from them?

My code:
console.log(threadArray)
returns this in console: (which is perfect)
enter image description here

but when I try to replace "threadArray" with "threadArray[0].threads[0]["_id" to get the first thread’s ID, it says it Cannot read unknown value.

Does anybody know why?

fabric canvas pointer is misaligned when using css.zoom property

when I use fabric canvas and use css zoom property.
drawing in the cancas draws with some offset.
How can I correct the cursor position?

<div style="zoom: 50%">
 <div id="fabric_canvas"></div>
</div>

the reason why I put zoom property in wrapper div is that the canvas is supposed to be rendered image, and manually edited by drawing mode and to be exported as image. I’d like to keep the good resolution.

Github rest api do not return correct list of data

I am trying to get the top 10 repositories based on the star, So here is the API I am using.

However, The result I get is incorrect and it seems like it changes the order of the top 3 repositories.
For example:
The first time I call the below API, here is the top 3 repository based on the star.

  1. freeCodeCamp/freeCodeCamp 342K
  2. EbookFoundation/free-programming-books 225K
  3. vuejs/vue 194K

After 1 minute, i call the api one more time and got totally different result:

  1. freeCodeCamp/freeCodeCamp 342K
  2. 996icu/996.ICU 261K
  3. jwasham/coding-interview-university 212K

So basically, the result is not correct. Is there anything wrong with my API endpoint?

https://api.github.com/search/repositories?q=stars:>0&sort=stars&per_page=3

Speech to text wit.ai telegram bot

I’m making a telegram bot. Using node js (node-telegram-bot-api), axios, wit.ai. Voice to text not working. What i doing wrong?

require('dotenv').config()
const TelegramApi = require('node-telegram-bot-api')
const bot = new TelegramApi(process.env.TOKEN, { polling: true })
const axios = require('axios')

bot.on('voice', async (msg) => {
  const stream = bot.getFileStream(msg.voice.file_id)

  let chunks = []

  stream.on('data', (chunk) => chunks.push(chunk))
  stream.on('end', () => {
    const axiosConfig = {
      method: 'POST',
      url: 'https://api.wit.ai/speech',
      headers: {
        Authorization: 'Bearer ' + WIT_API_KEY,
        'Content-Type': 'audio/ogg',
      },
      data: Buffer.concat(chunks),
    }
    axios(axiosConfig)
      .then((response) => {
        console.log('answer', response.data)
      })
      .catch((err) => {
        console.log('error', err)
      })
  })
})

enter image description here

How Can I Make a conditional with return in a .map without get out of main function?

My objetive is create this object:

{
  name: string.
  birthday: date;
}

by this array:

const dataArray = [
 {
  "id": "name",
  "type": "string";
 },
 {
  "id": "birthday",
  "type": "date";
 }

]

So, I create a .map of the array, like this:

const inputsValues = {};

dataArray.map(item => {
  if(item.type === "date"){
    inputsValues[item.id] = new Date(item.value);
    return; // this line is the problem
  }

  inputsValues[item.id] = item.value;
});

Is there a option to make a return in this function without use else?

Web Scraping Journal “El Peruano” – Python/Scrapy

im trying to scrap some info from “El Peruano” journal, but i cannot at first sight it look have to:

El Peruano Website

  1. Put a Date in a Formbox.
  2. Do a click in SearchBox.
  3. Get all links for get all: “Title”,”Resolution#”, “Body”

This is my code:

import scrapy

class SpiderPeruano(scrapy.Spider):
    name = "peruano"
    start_urls = [
        "https://diariooficial.elperuano.pe/Normas"
    ]

    custom_settings= {
        "FEED_URI": "peruano.json",
        "FEED_FORMAT": "json",
        "FEED_EXPORT_ENCODING": "utf-8"
    }

    def parse_click(self, response):
        
        #i put here a condition but i think is not necessary
        #button = response.xpath("//div[@id='busqueda']/form[@action]/button[@id='btnBuscar']").get()
        #if buttom:
        yield scrapy.FormRequest.from_response(
            response,
            formxpath= "//form[@id='space_PortalNormasLegalesN']",
            formdata={"cddesde": "08/03/2022", "cdhasta:": "08/03/2022"},
            dont_click=True,
            dont_filter=True,
            callback=self.parse
            )
 
            
    def parse(self, response):
    
        links = response.xpath("//div[@class='ediciones_texto']/h5/a/@href").getall()
        for link in links:
            yield response.follow(link, callback=self.parse_link)


    def parse_link(self, response):
        title = response.xpath("//div[@class='story']/h1[@class='sumilla']/text()").get()
        num = response.xpath("//div[@class='story']/h2[@class='resoluci-n']/text()").getall()
        body = response.xpath("//div[@class='story']/p/text()").getall()

        yield {
            "title": title,
            "num": num,
            "body": body
        }

#call
#scrapy crawl peruano

#url = "https://diariooficial.elperuano.pe/normas"

#Form_BOX: "//form[@action]"
#Box_desde = "//form[@action]/input[@id='cddesde']"
#Box_hasta = "//form[@action]/input[@id='cdhasta']"
#Button= "//div[@id='busqueda']/form[@action]/button[@id='btnBuscar']"

#links = "//div[@class='ediciones_texto']/h5/a/@href"
#titles= "//div[@class='story']/h1[@class='sumilla']/text()"
#resolutionNum= "//div[@class='story']/h2[@class='resoluci-n']/text()"
#body= "//div[@class='story']/p/text()"

So, i need some help for know what i’m doing wrong on my code cuz this run well but dont get the data.

Thx a lot for your time and help!

In Node.js, How can I access exported module in Index.js?

I have searched in stackoverflow and it seems there isn’t any use case like mine.
I have a structure folders like this in functions directory:

functions/index.js

I added some codes to be used by other functions like this in index.js:

require("dotenv");
const admin = require("firebase-admin");
const config = JSON.parse(process.env.FIREBASE_CONFIG);
admin.initializeApp(config);

const highLevel = {
  timeoutSeconds: 300,
  memory: "2GB",
};

const secretLevel = {
  timeoutSeconds: 120,
  memory: "1GB",
  secret: [process.env.SERVER_BACKEND],
};

const lowLevel = {
  timeoutSeconds: 120,
  memory: "512MB",
};

module.exports = lowLevel, highLevel, secretLevel;

I created a file in a folder structure like this:

functions/admin/features/music/publisher.js

How can I access the variable of lowLevel from publisher.js as I tried using this:

const lowLevel = require("../index");

and I can’t get any of reference to index.js. Is there a way to access file index.js from the root folder? Thank you very much for any tips and trick.