eventListener issue with WebComponent with preact and react wrapper

I am working to solve an bug in an open source project, emoji-mart. The emoji-picker is originally a webcomponent in (packages/emoji-mart) (pure component with preact), but they provide a react wrapper for it in packages/emoji-mart-react. I’ve been trying to solve this problem tldr: When a button in react is clicked to open the emoji-picker, it opens the first time. It renders so an eventlistener with document.addEventListener('click, handleOutsideClick) is added, when you click anywhere outside the emoji-picker, it closes, and I see in devtools that the event handler is removed from the <html> tag. When I go to click on the button to open it again, the functionality of the ‘supposedly’ removed event listener seems to have transferred to the button (I know this because I have added a print statement in handleClickOutside, Everywhere outside of the button nothing prints.). This causes the emoji-picker never to open again. I think this problem has to do with react synthetic events.

I have kinda found a way to fix this, I reverse the order of the bubbling, capture. This is not a good solution though because this causes it so that the synthetic event to close is called first and then open, so this causes it to never close anymore when you click on the button (it does close though when not clicked on btn).

How to call django view onclick then redirect

I’m trying to make a searchbar in my django app. When I click on a result from the searchbar I want it to call my view. I want the view to keep the context from what was clicked, perform a function, and then redirect me.

In my views.py

def search(request):
    query = request.GET.get('q', '')
    if query:
        sp = SpotipyConnection(client_id=sp_client_id, client_secret=sp_client_secret)
        #context = {'search': sp.searchbar(query)}
        context = {'search': sp.songSearch(query)}
        return render(request,'main/search.html',context=context)
    return render(request,'main/search.html',{})

def search_results(request):
    if request.method == 'POST':
        #TODO how do i get the context of what was clicked 
        songName = None
        songArtist = None
        context = openAISearch(artist=songArtist,song=songName)
        return render(request,'main/search_results.html',context=context)

In my search.html:

{% block title %}
Search
{% endblock %}

{% block content %}

<script>
  function redirectToHome(songName, songArtist) {
     <!-- TODO how do I call my search_results function then return the redirect -->
  }
  </script>

<form method="GET" action="{% url 'search' %}">
    <input type="text" name="q" id="search-input">
    <button type="submit">Search</button>
  </form>
  
    </form>
  {% if search %}
  {% for result in search %}

<p onclick="redirectToHome({{ result.name }},{{ result.artists.0.name }})"> {{result.name}} by {{ result.artists.0.name }} <img src="{{ result.album.images.0.url }}" alt="{{result.name}} image" style="width: 200px; height: 200px;"> </p> 
{% endfor %}
{% endif %}
{% endblock %}```

CSS: :focus-within not working on dynamic JavaScript-generated content

I’m displaying search suggestions as anchors inside the dropdown of a searchbar. If there’s focus-within the .searchbar element, the dropdown is visible. This works when I type the dropdown suggestions by hand but as soon as I use Javascript to generate them, the focus-within stops working.

HTML:

<div class="searchbar float float-up delay05">
    <input type="text">
    <div class="dropdown suggestions"></div>
</div>

CSS:

.searchbar:focus-within .suggestions{
    opacity: 1;
    visibility: visible;
    top: 43px;
}

JavaScript:

searchinput.oninput = generateSuggestions;

function generateSuggestions(){
    searchbar_dropdown.innerHTML = '';
    for(suggestion of show_suggestions){
        const a = document.createElement('a');
        a.src = 'explore.php?search='+suggestion['suggestion'];
        a.innerText = suggestion['suggestion'];
        searchbar_dropdown.appendChild(a);
    }

// I tried these two but it isn't working
    window.requestAnimationFrame();
    searchbar_dropdown.offsetHeight;
}

javascript pseudocode practice. Basic problem solving [duplicate]

Could someone tell me what mistake I’m making that’s causing not having the same outputs as the result.

First file:

function four() {
    return 4 + plus();
}

function nine() {
    return 9;
}

function plus() {

    return nine();
}

console.log(four(plus(nine())))
// Output: 13

Second file:

// I’ve added the above code into classes for demonstration purposes but it gives an error.

class A {
    four() {
        return 4 + plus();
    }

    nine() {
        return 9;
    }

    plus() {

        return nine();
    }
}
class B {
    constructor() {
        this.a = new A();
    }
    result() {
        console.log(this.a.four(this.a.plus(this.a.nine())))
    }
}
var r = new B();
r.result();
// Output: return nine();
           ^
ReferenceError: nine is not defined

Thank you in advance.

Call a funcation and pass a parameter in JS

I am trying to call a function called mytask and pass index variable as a parameter. However, it seems that the compiler doesn’t recognize index.

Here is my code:

fillTask();

function fillTask() {
  tasksList.innerHTML = '';
  let index = 0;
  for (task of tasks) {
    let li = document.createElement('li');
    li.innerHTML = ' <button onclick="mytask(${index})" class="delete">Delete</button> ';
    tasksList.appendChild(li);
    //index++;
  }
}

//Delete task
function mytask(index) {
  alert("Task has been deleted");
}

When I click on the delete button I am getting this error in my console:
Uncaught SyntaxError: missing ) after argument list (at index.html:1:8)

PIXI.Loader.shared is Undefined

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/7.2.4/pixi.js"></script>
</head>
<body>
<script>
    const app = new PIXI.Application({
            width: window.innerWidth,
            height: window.innerHeight,
            transparent: true
        });
        globalThis.__PIXI_APP__ = app;
        
        app.renderer.background.color = 0x23395D;
        app.renderer.view.style.position = 'absolute';
        document.body.appendChild(app.view);
        
        PIXI.Loader.shared
            .add('tileset', './img/tileset.png')
            .load((loader, resources) => {
                const texture1 = resources.tileset.texture;
                const rect1 = new PIXI.Rectangle(50, 50, 76, 86);
                texture1.frame = rect1;
                const sprite1 = new PIXI.Sprite(texture1);
                app.stage.addChild(sprite1);
            });
</script>
</body>
</html>

In this code in PIXI.Loader.shared i get

Uncaught TypeError: Cannot read properties of undefined (reading 'shared')

In Pixi.js docs this method is present, but in fact doesnt working. I also trying PIXI.loader and other similar methods from docs but it also doesnt work. What i’m doing wrong?

Require a special member role in WooCommerce for specific products

I need help to create a code.
I found this and im using this as main, but its not enough.
Require registration in WooCommerce for specific product

After the customer registers, they need to contact us before ordering.
After they have contacted us, we will upgrade their account to forexample as a subscriber.
Only subscribers can order the products ive listed as ID in the PHP.

  • Customer creates an account, normal customer account.
  • Customer add the product to cart, going to checkout —> “restricted” — must contact us before ordering.
  • They contact us, we upgrade their account to forexample subscriber.
  • Now they can buy the product.

I hope someone can help! 😀

Im using this at the moment, but its not enough for my requirements:

function filter_woocommerce_checkout_registration_required( $bool_value ) {
    // Several can be added, separated by a comma
    $product_ids = array ( 30, 813 );
    
    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Product ID from cart item in specific array
        if ( in_array( $cart_item['product_id'], $product_ids ) ) {
            // Registration_required
            $bool_value = true;
                    
            // Break loop
            break;
        }
    }

    return $bool_value;
}
add_filter( 'woocommerce_checkout_registration_required', 'filter_woocommerce_checkout_registration_required', 10, 1 );

Not able to grab the second array element

var longestCommonPrefix = function(strs) {

  var word = "";
  for (var i = 0; i < strs.length; i++) {
    var firstWord = strs[i];
    var secondWord = strs[1 + i];
    if (strs[i].length >= secondWord.length) {
      for (var d = 0; d < strs[i].length; d++) {
        var store1 = firstWord[d];
        if (secondWord.indexOf(store1) != -1) {
          word += store1;
        } else {
          word = "";
        }
      }
    } else {
      for (var f = 0; f < strs[i + 1].length; f++) {
        var store2 = firstWord[f];
        if (firstWord.indexOf(store1) != -1) {
          word += store2;
        } else {
          word = "";
        }
      }
    }
  }
  return (word);
};

I am trying to check the characters of two words in an array and store it in.

Issue, my secondWord is not able to grab the second element of array strs

How to pass actual values to minimist instead of key-value?

https://www.npmjs.com/package/minimist

For some keys I want to be able pass actual variables of them instead:

$ node my_script.js --var1 a --var2 b --var3 c

===>

$ node my_script.js --var1 a --b --var3 c
$ node my_script.js --var1 a --b1 --var3 c
$ node my_script.js --var1 a --b2 --var3 c

Where (b, b1, b2, ... bN) — is a predefined set of constants.

How to do it? Is it possible at all?

How do i route to single product page after user selection

i have this main products page which fetch all the products from a local json file

   interface productItem {
      id: number;
      name: string;
      image: string;
      price?: string;
      prices: {
        half: string;
        full: string;
      };
      categories: string;
    }

  const [products, setProducts] = useState("Cakes");
  const [sltproducts, setSltProducts] = useState<productItem[]>([]);

  useEffect(() => {
    const fetchProduct = () => {
      fetch("items.json")
        .then((response) => response.json())
        .then((productdata) => {
          const productcakes = productdata.Cakes.map((item: productItem) => ({
            ...item,
            categories: "Cake",
          }));
           const productmemorella = productdata.Memorella.map((item: productItem) => ({
             ...item,
             categories: "Memorella",
           }));
           const producticecream = productdata.Ice_Cream.map(
             (item: productItem) => ({
               ...item,
               categories: "Ice Cream",
             })
          );
          const productpastries = productdata.Pastries.map(
            (item: productItem) => ({
              ...item,
              categories: "Pastries",
            })
          );
          setSltProducts([...productcakes,...productmemorella, ...producticecream, ...productpastries]);
        })
        .catch((error) => {
          console.error("Error fetching items:", error);
        });
    }
    fetchProduct();
  }, [])

This is my card component on same page

{sltproducts
                .filter((product) => product.categories === "Cake")
                .map((prdct) => (
                  <Link
                    href={`/Product/${prdct.categories}/${prdct.id}`}
                    key={prdct.id}
                    className="product-page-selected-cakes-card"
                  >
                    <img src={prdct.image} alt="" />
                    <div className="product-price">
                      <h5>{prdct.name}</h5>
                      <hr />
                      <p>₹{prdct.prices.half}</p>
                    </div>
                  </Link>

This is my single product folder which i have give [] for dynamic route
file

How do i fetch a single product that was selected by the user to this single product page. Note that “product.categories” is because i have multiple section i.e cakes, pastries etc

Chat component sets DocumentID as null in Firebase

I have been working on a chat feature and I have had this problem for a while, I’ve tried everything I can think of to solve (not hard enough obviously lol) and am stumped once again; I’m calling on the problem-solving souls of StackOverflow to hopefully see something I’m not seeing

Here is my ChatInput code, this has a text input box for the user to send a message. Once it does it’s supposed to update an already existing collection in firebase (called “chats”) with the combined userID of both users who are messaging each other, however, each time a message is sent, the docID is updated to null.

Input.jsx

import React, { useContext, useState } from "react";
import Img from "../assets/img.png";
import Attach from "../assets/attach.png";
import { useAuth } from "../contexts/AuthContext";
import { ChatContext } from "../contexts/ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);

  const { currentUser } = useAuth();
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (!data.chatId) {
      console.error("Chat ID is not set, cannot update the document.");
      return;
    }
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
             const messageRef = await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };
  return (
    <div className="input">
      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />
      <div className="send">
        <img src={Attach} alt="" />
        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />
        <label htmlFor="file">
          <img src={Img} alt="" />
        </label>
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  );
};

export default Input;

And here is my ChatContext…

ChatContext.jsx

import {
    createContext,
    useReducer,
  } from "react";
  import { useAuth } from "./AuthContext";
  
  export const ChatContext = createContext();
  
  export const ChatContextProvider = ({ children }) => {
    const { currentUser } = useAuth();
    const INITIAL_STATE = {
      chatId: "null",
      user: {},
    };
    
    console.log("currentUser", currentUser);
    console.log("INITIAL_STATE", INITIAL_STATE);
    const chatReducer = (state, action) => {
      switch (action.type) {
        case "SET_USER":
          const { uid, name } = action.payload;
          const chatId =
            currentUser.uid > uid ? currentUser.uid + uid : uid + currentUser.uid;
          return {
            chatId,
            user: { uid, name },
          };
        default:
          return state;
      }
    };
  
    const [state, dispatch] = useReducer(chatReducer, INITIAL_STATE);
  
    const setUser = (uid, name) => {
      dispatch({ type: "SET_USER", payload: { uid, name } });
    };
  
    return (
      <ChatContext.Provider value={{ data: state, setUser }}>
        {children}
      </ChatContext.Provider>
    );
  };
  

My suspicion is with the ChatContext, it doesn’t dispatch the switch case and just stays in the INITIAL_STATE, which will set the user as “null,” however I’ve tried to change this, even putting the dispatch in the Input.jsx code, but no changes. I’ve tried changing the chatID to null instead of including the double quotes, but that seems to make it worse.

Any input is truly appreciated as I have no idea where to go from here.

How to convert the sunset UNIX timestamp from OpenWeather API to local time using JavaScript?

I’m using the OpenWeather API to get the sunset time for a specific city. The API returns the sunset time as a UNIX timestamp, and I want to convert this timestamp into the local time of the specific city using JavaScript.

  "sys": {
    "type": 1,
    "id": 5122,
    "country": "US",
    "sunrise": 1587168307,
    "sunset": 1587216456
  },

I’ve tried creating a new Date object using the sunset timestamp like this:

var sunsetTimestamp = 1587216456;
var sunsetDate = new Date(sunsetTimestamp);
console.log(sunsetDate)

However, this doesn’t give me the correct local time of sunset.

How to save and add width and speed from json.graph file into edges(links)

    {
      "directed": false,
      "multigraph": false,
      "graph": {},
      "nodes": [
        {
          "pos": [
            40.7842494,
            -73.9470901
          ],
          "id": 42443054
        }
  ],
  "links": [
    {
        {
          "attr": {
            "speed": "20 mph",
            "width": "2'",
            "label": "edge 11 secondary",
            "isPrimary": false
          },
          "source": 7067139595,
          "target": 7067139597
        }
      ]
    }

Here i have graph.json file.
what i did is that I imported and saved the nodes into my graph jsnx, but I am having very tough time in importing and saving the source, target, speed and width from the attr into my edges(links).

Please if someone can help me I would really really appreciate, due to a lot of information online I am really so lost.

Thanks in advance!

Problem using eventhandler to show video on subpage according to which image was clicked on mainpage (html, javascript , css)

I’m a noob in html, css and javascript and i’m making a project for my students.
I’ve made a main page called index.html and a subpage called visningsside.html (pardon the danish) and linked to external CSS and Javascript (which works fine).
I want two images called film1 and film2 to tricker a function, when clicked. The function should, according to which image was clicked, load an iframe with embeded-link to youtube on the subpage, and change the page to show the sub page.
The page changes, when the images are clicked, but the iframe isn’t changing.
I’m using replit as editor.

You can see, comment, edit and run the project at replit

I’ve tried to add DOMContentLoaded to the script in order to avoid problems with html-elements not loaded before the script executes. Perhaps i should try to use onclick instead of an eventlistener, but i thought it was nice to use event target as a parameter to determine which image was clicked.