How to use Jquery load along with functions?

So I am using Jquery load to load navigation bar on my website.
Here’s how im doing it

Homepage.html

<div id="nav-placeholder">

</div>
<script>
      jQuery(document).ready(function($) {
        jQuery("#nav-placeholder").load("navbar.html");
      });
</script>

navbar.html

<div class="navbar">
  <a href="#">Phemesoft</a>
  <a href="/studdash">Dashboard</a>
  <a href="/courselists">Courses</a>
  <a href="#">Live classes</a>
  <a href="#">Labs</a>
  <div class="search">
    
    <input id="searchqueryy"  name="searchquery" type="search" placeholder="Search" class="inputSearch" />
     <button onclick="searchfunction()" type="submit" class="searchButton">
           <i class="fa fa-search"></i>
        </button>
        
  </div>
  <!-- <button type="submit" class="searchbtn">
    <span class="material-icons">search</span>
  </button> -->
  <span class="material-icons">shopping_cart</span>
  <span class="material-icons">account_circle</span>
</div>

Since I have a server running, to load the navbar I have used app.get like so:

app.get("/navbar.html",function(request,response){
  response.sendFile(path.join(__dirname, "../client/App/", "navbar.html"));
});

And the search function looks like this:

<script>
  function searchfunction(){
    var searchquery = document.getElementById('searchqueryys').value;
    window.location.href = "/search/"+searchquery;
  }
  </script>

Now the problem is, after loading the navigation bar using jQuery.load, searchfunction isn’t working. I tried putting the searchfunction() script inside navbar.html but it doesn’t work like that (maybe because navbar.html has already been loaded when homepage.html was opened?). So how do I make my search function work across pages while using jQuery.load?

using form data to send request similar to JSON

I’m making a web app (next.js) that’s pretty similar to fiverr. basically my update gig API endpoint requires that the request body be something like this:

{
  gig: { ...fields_related_to_gig },
  portfolioItems: [ {
    title: "",
    description: "",
    image: // a file
  } ] // basically the items that get displayed in your gig's portfolio
 }

Because im sending files with the request I need tp use form data. but then again I have arrays and nested objects which dont translate well into form data. I need some guidance as to how to pull this off. Should I straight up change the request format? should I JSON.stringify everything on front and decode on backend?

what are the best practices when it comes to sending files along with arrays of objects in the request body?

setInterval() still triggering after clearInterval() in NodeJS

I have the following code setting and clearing an interval inside a NodeJS script.

Starting interval works fine, but when trying to clear it, the stopping interval console will trigger, but the interval will continue firing every minute.

app.get("/api", async (req, res) => {

    active = req.query.active;
    
    let interval = null;

    if (active == "true") {

        console.log("starting interval");

        interval = setInterval(async function() {
            try {
                const Posts = await getPosts();
                const Comments = await getComments();
                sendPosts().then(() => sendComments());

            } catch (e) {
                throw e;
            };
        }, 60000);

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: true});

    } else {

        console.log("stopping interval");

        clearInterval(interval);
        interval = null;

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: false});
    }
    
});

What am I missing?

Rotating Line around Point in p5.js

Goal: I’m trying to create a triangle given two angles (a0,b0). To do so, I’m trying to rotate a vector r0 by some angle a0 around one of the vertices of r0. Here’s a diagram illustrating my idea.
enter image description here
Problem: However, when I rotate the line, it seems to rotate around the origin. I’ve read many, many articles on how to fix this, but none of the suggested solutions (i.e., translate then rotate, push(), pop()) don’t seem to work, perhaps because I’m dealing with a line segment here. Below is my code.

MWE Code:

let angle = 0;

function setup(){
  createCanvas(600, 400);
  angleMode(DEGREES);
}

function draw(){
  let v1 = createVector(width/2 - 50, height/2);
  let v2 = createVector(width/2 + 50, height/2);

  background(255);
  stroke(0);
  strokeWeight(4);
  rotate(-1 * mouseX);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>

    <title>Billiards #2</title>
  </head>
  <body>
    <script src="sketch.js"></script>
  </body>
</html>

Any help is appreciated.

Mongoose add parentdoc if it doesn’t exist OR add subdoc if parent doc exists but subdoc doesn’t

Essentially, I have a User that has an email and a list of subscriptions. I want to create the User with the subscription if the user doesn’t exist, if the user exists but doesn’t have the subscription I Want to simply add the newSubscription to the Users list of subscriptions. Finally, if both User and subscription already exist then I want to handle the existing subscription in my own way.

await UserDocument.findOneAndUpdate(
            {'$and': [{
                'email': email,
            }, {
                'subscriptions.product': product-id,
            }]},
            {'$setOnInsert': newCustomerWithSubscription,
            '$push': {'email.$.subscription': newSubscription}},  
            {upsert: true, new: false},
            async function(err: CallbackError, doc: UserSchemaType | null) {
                //Code to handle if both exists
            }).exec();

DB Design:

User: {
    email,
    subscriptions: [{
        //sub-info
    }]
}

How can I get the actual height of the content,when -webkit-line-clamp: 2;-webkit-box-orient: vertical; and overflow:hidden is applied

So I have used two div to explain my question both div .text and text2 contains same data but .text has below CSS property:

.text {
   overflow: hidden;
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   transition: all 0.3s ease-in-out;
}

which text 2 has not,both has same data so but I want to know .text actual height even if above CSS applied.

document.getElementById('text2').innerHTML = "Height of below div is: " + document.querySelector(".text2").offsetHeight;

document.getElementById('text').innerHTML = "Height of below div is: " + document.querySelector(".text").offsetHeight;
.text {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: all 0.3s ease-in-out;
}
<div class="box">
  <p id="text"></p>
  <div class="text">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
  <br><br>
  <p id="text2"></p>
  <div class="text2">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div>

Error with Html Webpack Plugin when I start my app

When I start my new react app I get an error:

Html Webpack Plugin:
  Error: Child compilation failed:
  Module build failed (from ../../#React/react-sneakers/node_modules/html-webpack-plugin/lib/loader.js):
  Error: Cannot find module 'C:Users1Desktopworks#Reactreact-sneakersnode_moduleshtml-webpack-pluginlibloader.js'
  Require stack:
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibloadLoader.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpack-manifest-plugindistindex.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesreact-scriptsconfigwebpack.config.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesreact-scriptsscriptsstart.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:1005:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at loadLoader (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibloadLoader.js:19:17)
      at iteratePitchingLoaders (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:18  2:2)
      at runLoaders (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:397:2)
      at NormalModule._doBuild (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:814:3)
      at NormalModule.build (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:958:15)
      at C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibCompilation.js:1369:12
  ModuleBuildError: Module build failed (from ../../#React/react-sneakers/node_modules/html-webpack-plugin/lib/loader.js):
  Error: Cannot find module 'C:Users1Desktopworks#Reactreact-sneakersnode_moduleshtml-webpack-pluginlibloader.js'
  Require stack:
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibloadLoader.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpack-manifest-plugindistindex.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesreact-scriptsconfigwebpack.config.js
  - C:Users1Desktopworks#Reactreact-sneakersnode_modulesreact-scriptsscriptsstart.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:1005:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at loadLoader (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibloadLoader.js:19:17)
      at iteratePitchingLoaders (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:18  2:2)
      at runLoaders (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:397:2)
      at NormalModule._doBuild (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:814:3)
      at NormalModule.build (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:958:15)
      at C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibCompilation.js:1369:12
      at processResult (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:753:19)
      at C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:855:5
      at C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:399:11
      at C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:185:11
      at loadLoader (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibloadLoader.js:33:11)
      at iteratePitchingLoaders (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:18  2:2)
      at runLoaders (C:Users1Desktopworks#Reactreact-sneakersnode_modulesloader-runnerlibLoaderRunner.js:397:2)
      at NormalModule._doBuild (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:814:3)
      at NormalModule.build (C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibNormalModule.js:958:15)
      at C:Users1Desktopworks#Reactreact-sneakersnode_moduleswebpacklibCompilation.js:1369:12

Node v: 16.13.2
npm v: 8.5.0

What should I do?

This happened when I reinstalled Node.js
Perhaps this is due to some error during reinstallation
Please, if you have encountered such a problem, write what helped you.

Could to translate JQuery code to JavaScript. And is there any working converter jq to js and vice verse? [duplicate]

//JQuery
$(“#toggle-btn”).click(function () {
$(“#sidebar”).toggleClass(“active”); //add class just to change the sidebar position
$(“#toggle-btn”).toggleClass(“activeBtn”);
return false; // prevent to pass click event to body
});

$("body").click(function () {
  if ($("#sidebar").is(".active")) {
    $("#sidebar").toggleClass("active");
    $("#toggle-btn").toggleClass("activeBtn");
  }## Heading ##
});

$("#sidebar").click(function (e) {
  e.preventDefault();
  return false;
});

Vuetify v-autocomplete doesn’t render dynamic items

I have a dynamic list that gets updated upon search. I’ve tried using no-filter and :filter="v => v" and such solutions.

Problem: sometimes the list gets updated, sometimes it doesn’t. If I search for tra, it shows the list, but searching again for something else, it will show no data. If I click on the x icon to clear the input, it shows the list.

Debugging the Vue tools, I’ve seen that the items do get inserted into the dialog_payload.users. Nevertheless, it’s an issue with the autocomplete.

I’m searching for a way to force refresh the component.

Discord’s channel stated that it has something to do with Vue depth reactivity, but I’m already using splice & push to trigger it.

v-autocomplete

  <v-autocomplete no-filter v-model="item_payload.item" class="selection-controls-padding" solo flat hide-details :background-color="$vuetify.theme.dark ? '#292929' : '#edeff0'"
                                  label="Search by name, committee or role..." clearable hide-selected hide-no-data prepend-inner-icon="mdi-magnify" :search-input.sync="dialog_payload.search" append-outer-icon="mdi-cog"
                                  @click:append-outer="openFilters()" ref="test" :items="dialog_payload.users" return-object item-id="id" @change="dialog_payload.search = ''" item-text="title" :loading="dialog_payload.loading_list">
                                    <template v-slot:item="{index, item}">
                                        <v-list-item-avatar color="grey" size="30">
                                            <v-img v-if="item.profile_picture" :src="`${$Helper.files_paths.profile_pictures}${item.avatar}`"></v-img>
                                            <v-icon v-else size="24" color="white">mdi-account-circle</v-icon>
                                        </v-list-item-avatar>
                                        <v-list-item-content>
                                            <v-list-item-title>{{item.smart_name}}</v-list-item-title>
                                            <v-list-item-subtitle>{{item.full_name}}</v-list-item-subtitle>
                                        </v-list-item-content>
                                    </template>
                                </v-autocomplete>

watch

"dialog_payload.search"(newValue) {
            if (newValue && newValue !== "" && newValue.length > 1) {
                let app = this
                clearTimeout(app.dialog_payload.timeout)
                app.dialog_payload.timeout = setTimeout(function() {
                    app.dialog_payload.loading_list = true
                    app.getSuggestions(newValue)
                }, 400);
            }
        },


"item_payload.item"(newValue) {
            if (newValue) {
                let app = this
                app.dialog_payload.search = ""
                let found = app.item_payload.users.some(item => (item.id === newValue.id))
                if (!found) {
                    app.item_payload.users.push(newValue)
                }

                app.item_payload.item = null
                app.dialog_payload.users = []

            }
        }

Inside getSuggestion on then success

let users = response.data.users
                app.dialog_payload.users.splice(0)
                app.dialog_payload.users.push(...users)

                console.log(app.$refs.test)

                app.dialog_payload.loading_list = false

How to ‘melt’ a wide table/array in google app script?

I have an array/table in Google Sheets with data in the following format:

Catergory1 A A A A A B B B B B C C C C C
Catergory2 Q1 Q2 Q3 Q4 Q5 Q1 Q2 Q3 Q4 Q5 Q1 Q2 Q3 Q4 Q5
Propotions 34% 66% 9% 49% 31% 36% 69% 1% 10% 20% 98% 38% 21% 57% 76%

I want to use Google App Script to convert this array into the following format:

Catergory1 Q1 Q2 Q3 Q4 Q5
A 34% 66% 9% 49% 31%
B 36% 69% 1% 10% 20%
C 98% 38% 21% 57% 76%

Thanks in advance.

I’m getting a error where webrtc is not returning the current videos that is being broadcasted, Im using react

I have a different component that is responsible for streaming and this
component
is for listing the streams out so eventually they can be selected. the problem
here is the streams are here in the event object but I can’t view them
the peerConnection.ontrack actually working because I was able to get the
streams.
but the problem is the srcObject
uncaught TypeError: Cannot add property srcObject, object is not extensible
that is the error it returning

import React, { useEffect, useContext, useState, useRef } from 'react';

import  { io }  from 'socket.io-client'
const socket = io('http://localhost:8080')


let peerConnection;



const Watcher = () => {
  const [myStream, setStream] = useState([]);

  const appCxt = useContext(AppContext)

  const myVideo = useRef(null)
  const config = appCxt.config

  useEffect(() => {

    socket.on("offer", (id, description) => {

      peerConnection = new RTCPeerConnection(config);
      peerConnection
        .setRemoteDescription(description)
        .then(() => peerConnection.createAnswer())
        .then(sdp => peerConnection.setLocalDescription(sdp))
        .then(() => {
          socket.emit("answer", id, peerConnection.localDescription);
        });


       
          peerConnection.ontrack = (event) => {

             myVideo.current.srcObject = event.streams[0]
          };
          peerConnection.onicecandidate = event => {
            if (event.candidate) {
              socket.emit("candidate", id, event.candidate);
            }
          };
    
        });
        socket.on("candidate", (id, candidate) => {
          peerConnection
            .addIceCandidate(new RTCIceCandidate(candidate))
            .catch(e => console.error(e));
        });
        
        socket.on("connect", () => {
          socket.emit("watcher");
        });
        socket.on("broadcaster", () => {
          socket.emit("watcher");
        });
      }, [])
    
      return (
        <>
        </>
      )
    }
    ```
    
    

How to to make a mini os on js?

Is it possible to create an operating system that simply boosts and after that opens a desktop where I want to put only one exe application (web browser)?

How to do that?
In what programming language?

Javascript in-place reversing array [duplicate]

I’m new to javascript, I’m trying to modify the string passed as argument to function.

const message = "Reverse";

function reverseWords(message) {

  let leftIndex = 0;
  let rightIndex = message.length - 1;

  // Walk towards the middle, from both sides
  while (leftIndex < rightIndex) {

    // Swap the left char and right char
    const temp = message[leftIndex];
    message[leftIndex] = message[rightIndex];
    message[rightIndex] = temp;
    leftIndex++;
    rightIndex--;
  }
console.log(message) //Output Reverse; I don't know why
}

reverseWords(message);

I know C language there string is store like this in memory [R,E,V,E,R,S,E,], but I’m confused why the function isn’t updating my message array.

Please help me to visualize it

How to use one ajax code for multi purpose with callbacks in Js

Hi before opening this issue , I went through many posts from stackoverflow. But i couldn’t find my desired answer.

So Let me introduce my problem first.

I have a piece of code written in JSON object class.
In which you can see there is customers object having its function for adding New Customer. And a method for request Ajax calls

 var sys={
        
        customers:{
            addNew:function (ref,cb=null){
                if(!cb) { // so it can check if the call to this method was for requesting ajax request or handling its response . note i am sending the callback function reference same as the current
                    core.request({d: $('form').serialize()}, 'sys.customers.addNew', ref);
                }else{
                    if(ref.status){
                        $('.customers-list').append('<li>'+ref.customer.name+'</li>');
                        alert('success')
                    }
                }
            },
            updateRowAfterAdd:function (){
                // or i could use this for handling callback by passing its reference instead of the upper same function
            }
        },
        
        request: function (p = {}, c = null,e=false) {
            $.ajax({
                url: "/to/my/server",
                data: {p: p},
                type: 'post',
                dataType: 'json',
                beforeSend: function () {
                    
                },
                success: function (r) {
                    if (c != null)
                        (e?eval("(" + c + "(r,e));"):eval("(" + c + "(r));"));
                }
            });
        }
    }

Here is more explanation. If i want to use it i would go like this

    $(document).on('click','.addNew',function () {
         sys.customers.addNew($(this));
    });

So the idea in this example is to call the ajax method by passing a callback function reference for handling the SUCCESS response after it gets completed.
And if you look at addNew() method. It is working two way.. With the help of 2nd param ( cb ) it is determining that the call to this function was for sending Ajax request or handling its response back .

As i’m using in ajax’s success method eval() which is i know evil .
So i want to understand how i can do this without using EVAL method ? Because i have multiple things running on my page which needs ajax calls. and i don’t want them to rewrite for each of them.

And also i need this for ajax’s beforeSuccess() method as well.

How to get an array of date for a certain amount of days

How can I get an array of dates 5days from current date.
For Example
Today’s date is Sat, Feb 12, 2022 at my location currently.

So i how will i get an array of date 5days from now like the example below

const dateFromNow = [
  'Sat, Feb 12, 2022',
  'Sun, Feb 13, 2022',
  'Mon, Feb 14, 2022',
  'Tus, Feb 15, 2022',
  'Wed, Feb 16, 2022 ',
];