How to call an existing onclick function using javascript

I have this button that opens a modal when it is clicked.
I am trying to call the onclick function for the button via javascript instead of using the mouse.

I used the dom to get the element via classname and tried to call the onclick function but i couldn’t figure it out.

var elements = document.getElementsByClassName("shopify-buy__btn");
for (i=0; i<elements.length; i++) {
  if (elements[i].onclick) {
    elements[i].onclick(); // Run the "onclick" function.
  } 
}

Here’s the website with the button:

https://fantastic-choice-042131.framer.app/

Data-Attribute in HTML

I am unable to access full name of the product while accessing through Data-Attribute. It just gives me first word not the complete name of the product.

I am trying to access product’s name and quantity properties using Data-Attribute to add to another file but I am able to get only first letter of the name.

Next route showing 404 error when using Link from next/link

I am creating a login route. In a Navbar component I have added a Link to the login route inside a button tag, but when I hit the route it takes me to page which shows 404 error.

–app
—-pages
——component
——–Navbar.js
——login.js
—-global.css
—-layout.js
—-pages.js

Navbar component

import Link from "next/link";


export default function Navbar() {
    return (
        <div>
            <div className="flex flex-row bg-nav-bar-clr justify-between px-10 py-7">
                <h1 className="text-5xl font-extrabold italic text-klove">Klove</h1>
                <div className="flex gap-10">
                    <button className=" text-xl bg-signup-btn-clr px-8 py-2 rounded-3xl">Signup</button>
                    <Link href={'login'} className="text-xl bg-login-btn-clr px-8 py-2 rounded-3xl">Login</Link>
                </div>
            </div>
            <div className="flex justify-evenly my-4">
                <h1 className="text-2xl">HOME</h1>
                <h1 className="text-2xl">ABOUT</h1>
                <h1 className="text-2xl">CONTACT</h1>
            </div>

        </div>
    )
}

Django Websocket giving error when connecting in video call app

I am using Django websocket for making a real video chat app and I am beginner in Websocket.
I/m trying that user first give the room name and then the username and then it will be connected to the meeting room. I’ve written it like below

For Routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/(?P<room_name>w+)/(?P<name>w+)/$', consumers.ChatVideoConsumer.as_asgi())
]

For urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('<str:room_name>/<str:name>/', views.index, name='index'),
]

For Views.py

from django.shortcuts import render

# Create your views here.
def index(request, *args, **kwargs):
    return render(request, "chat/room.html")

For Room.js

console.log("Hello World from room.js");
console.log(window.location.pathname);

let wsStart = "ws://";
const loc = window.location;

if(loc.protocol === "https:") {
    wsStart = "wss://";
}

const endpoint = wsStart + loc.host + loc.pathname;
console.log("Endpoint", endpoint);
const websocket = new WebSocket(endpoint);

websocket.onopen = (e) => {
    console.log("Open", e);
};

// websocket.onmessage = (e) => {
//     console.log("Message", e);
// };

websocket.onclose = (e) => {
    console.log("Close", e);
};

For Consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class ChatVideoConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        print("connect")
        await self.accept()

        self.send(text_data=json.dumps({
            "type" : "Message.Accept",
            "message" : "Hello Connect Established"
        }))

    async def disconnect(self, close_code):
        pass


asgi.py

import os

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
import chat.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    # Just HTTP for now. (We can add other protocols later.)
    "websocket" : AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    )
})

Error Occuring:

WebSocket HANDSHAKING /yash/yash/ [127.0.0.1:43816]
Exception inside application: No route found for path 'yash/yash/'.
Traceback (most recent call last):
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__
    return await self.application(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/channels/routing.py", line 62, in __call__
    return await application(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/channels/sessions.py", line 47, in __call__
    return await self.inner(dict(scope, cookies=cookies), receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/channels/sessions.py", line 263, in __call__
    return await self.inner(wrapper.scope, receive, wrapper.send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/channels/auth.py", line 185, in __call__
    return await super().__call__(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/channels/middleware.py", line 24, in __call__
    return await self.inner(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/media/groot/New Volume/Myprojects/Django/Video_Chat_App/.venv/lib/python3.11/site-packages/channels/routing.py", line 134, in __call__
    raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'yash/yash/'.
WebSocket DISCONNECT /yash/yash/ [127.0.0.1:43816]

Kindly Give me solution for it.
Please.

How to use a module which needs import statement

I want to use this module in my nodejs app.

the issue is I used a lot of modules with require statement before, like:

const translate = require('google-translate-open-api');

Now when i want to use the mentioned module using this:

import { HttpProxyAgent } from 'http-proxy-agent';

I get this error:

SyntaxError: Cannot use import statement outside a module

if I use this code to import the module:

const HttpProxyAgent = require('http-proxy-agent');

I get this error:

TypeError: createHttpProxyAgent is not a function

How can I use this kind of modules in nodejs app?

Vue provide/inject logic

I want to fetch the current user if user is authenticated (the auth state I get from 0auth) and provide it to children components:

<script setup>
import { computed } from "@vue/reactivity";
import { provide, ref, watch } from "vue";

const fetchedUser = ref(null);
const error = ref(null);

const { isAuthenticated,user: authUser } = useSomething();

provide(
  "user",
  computed(() => fetchedUser.value)
);

watch(isAuthenticated, async (newAuthenticated) => {
  if (newAuthenticated) {
    const response = await fetch(`/api/users/${authUser.value.email}`, {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    if (response.ok) {
      const json = await response.json();
      // I load the user properly here, can access it
      console.log({ json });
      fetchedUser.value = json.user;
    } else {
      error.value = "Failed to get user";
    }
  }
});
</script>

Here is the child:

...
const currentUser = inject("user");

const k = ref(null);

watch(currentUser, (newValue) => {
  console.log({newValue});
  k.value = newValue;
});

console.log(k.value);
...

It always returns the initial value. I tried many things but can’t get it right.

Tailwind is not updating in real time

I am trying to create tailwind playground and i’m using CodeMirror and react-live package

when i write tailwind styles inside CodeMirror editor in source its there as renderers’ class but not updating in real time. imagine you are giving style to div with text input its there but not changing anything. if i put pre-ready code in react-live livePreview it works just fine.

example video: “https://www.veed.io/view/c8676a90-367f-4be1-bb56-e134665af00f?sharingWidget=true&panel=share”

code fragment:

     function Compiler() {
      const [code, setCode] = useState(`
        function App() {
         return (
          <div>
           <h1 className="text-red-800">Hello, React!</h1>
         </div>
        );
       }`);

       const onChange = React.useCallback((value, viewUpdate) => {
        setCode(value);
      }, []);

  

      return (
        <div className="flex">
          <ReactCodeMirror
            value={code}
            height="400px"
            width="800px"
            theme="dark"
            extensions={[javascript({ jsx: true })]}
            onChange={onChange}
            basicSetup={{
              foldGutter: true,
              allowMultipleSelections: true,
            }}
          />
          <LiveProvider code={code} scope={{React}}>
            <LiveError />
            <LivePreview />
          </LiveProvider>
        </div>
      );
    }

node.js server not responding, and not running

I’m pretty new to node and I’m trying to create a simple server for iOS notes app but when I type in node server.js in command prompt nothing happens.

`


//CREATE A NOTE
//Post request
app.post("/create", (req, res) => {

    var Note = new Data({

        note: req.get("note"),
        title: req.get("title"),
        date: req.get("data"),
    })

    note.save().then(() => {
        if (note.isNew == false){
            console.log("Save data!")
            res.send("Saved data")
        }else {
            console.log("Failed to save data")
        }
    })
})

// http://10.11.210.1:8081/create
var server = app.listen(8081, "10.11.210.1", function(){
    console.log("Server is running!")
})

enter image description here

Using querySelectorAll to toggle content’s display on/off

I’m relatively new to JS, I’m working on my personal project.

So there is a div container, inside the div container there is n number of sub-containers, which all have a button, and another div which is the content. I want each button of the sub-container to open and close the content when clicked. There can be as many sub-containers as possible, but each button of the sub-container should only be able to open/close its respective content.

For the sake of simplicity, I haven’t put the actual code of my project, because it includes a lot of unimportant icons and design elements, I think the example below can explain my problem.

I only put two sub-containers, but we should be able to add as many as possible.

In my own code, the first sub-container works perfectly, it opens and closes as expected, but by clicking on the second or third or the nth sub-container, it just opens and closes the first one’s content, not its respective one. I hope I’ve explained it clearly. Any help would be appreciated. Thanks.

function openContent() {
  let partContainer = document.querySelectorAll(".container");

  partContainer.forEach((parent) => {
    let part = parent.querySelector(".thisPart");
    let content = parent.querySelector(".content");

    if (content.style.display === "none") {
      content.style.display = "flex";
    } else {
      content.style.display = "none";
    }
  });
}
<div class="container">
  <div class="subContainer">
    <button class="thisPart" onclick="openContent()">Open Content 1</button>
    <div class="content">Content 1</div>
  </div>
  <div class="subContainer">
    <button class="thisPart" onclick="openContent()">Open Content 1</button>
    <div class="content">Content 1</div>
  </div>
</div>

How to properly type this typescript generic function

Given the example below:

const brands = { mercedes: "mercedes", audi: "audi" } as const;
type Brands = keyof typeof brands;

type MercedesFactory = {
    propA: string;
}

type AudiFactory = {
    propB: string;
}

type CarProps<TFactory> = {
    color: string;
    hp: number;
    factory: TFactory
}

type Mercedes = {
    c180: CarProps<MercedesFactory>,
    c220: CarProps<MercedesFactory>,
}

type Audi = {
    a3: CarProps<AudiFactory>,
    tt: CarProps<AudiFactory>,
}

const mercedes: Mercedes = {
    c180:
    {
        color: "blue",
        hp: 120,
        factory: { propA: "xx" }
    },
    c220: {
        color: "black",
        hp: 150,
        factory: { propA: "yy" }
    }
}

const audi: Audi = {
    a3:
    {
        color: "blue",
        hp: 120,
        factory: { propB: "zz" }
    },
    tt: {
        color: "red",
        hp: 150,
        factory: { propB: "aa" }
    }
}

const allCars: Record<Brands, Mercedes | Audi> = {
    mercedes,
    audi,
}

I want the generic function bellow to return Fabric information for all the blue cars, depends on the brand passed as parameter:

const getAllBlueCars = (brand: Brands) => {
    const carBrand = allCars[brand]; // Mercedes | Audi
    // object car is not typed correctly (any), and function returns any[]
    return Object.values(carBrand).reduce((acc, car) => {
        if (car.color === "blue") {
            return [...acc, car.factory];
        }
        return acc;
    }, [])
    // I'd like car is typed correctly and function returns an MercedesFactory[] or AudiFactory[], depends on which brand was passed like the example bellow
}

But as you can see below, it’s returning any;

const allAudiBlueCarsFabric = getAllBlueCars("audi"); // any

This works fine, car is typed correctly and it returns correct type:

const mercedesFactories = Object.values(mercedes).reduce<MercedesFactory[]>((acc, car) => (car.color === "blue" ? [...acc, car.factory] : acc), []);

// another simple example, using filter
const carMercedesFilterExample = Object.values(mercedes).filter((car) => car.color === "blue");

Typescript Playground Link


This is the Chat GPT Solution. The returned value is correct, but car is still typed wrong:

const getAllBlueCars2 = <TBrand extends Brands>(brand: TBrand) => {
    const carBrand = allCars[brand];

    // it works, but car is still typed as any
    return Object.values(carBrand).reduce<((TBrand extends "mercedes" ? MercedesFactory : AudiFactory)[])>((acc, car) => {
        if (car.color === "blue") {
            return [...acc, car.factory];
        }
        return acc;
    }, []);
};

const allAudiBlueCarsFabric2 = getAllBlueCars2("audi"); // AudiFactory[]

Security Guard Services in Noida

Get in touch with us today for all security solutions. As we are known for the best security guard services in greater noida and noida. CPS Security Guard Services Solutions is one of the leading security guard services agencies in Greater Noida (NCR) and Jhansi . Having all categories of security guards, gunman, and bouncer. We are the most reputed agency. If you are looking for the same please contact us on – +91- 8929784555 or visit our website –
https://cpsgrup.com/.

Get in touch with us today for all security solutions. As we are known for the best security guard services in greater noida and noida. CPS Security Guard Services Solutions is one of the leading security guard services agencies in Greater Noida (NCR) and Jhansi .

I want to apply different interval timing for the video in a owl-carousel in bootstrap having 3 images and a video with current interval of 5sec

$(“.header-carousel”).owlCarousel({
autoplay: true,
smartSpeed: 1500,
loop: true,
nav: false,
dots: true,
animateOut: ‘fadeOut’,
animateIn: ‘fadeIn’,
items: 1,
dotsData: true,
});

this is the js code for carousel

$(“.header-carousel”).owlCarousel({
autoplay: true,
autoplayTimeout: 1000;
smartSpeed: 1500,
loop: true,
nav: false,
dots: true,
animateOut: ‘fadeOut’,
animateIn: ‘fadeIn’,
items: 1,
dotsData: true,
});

this applies 10 sec time interval to all the slides and i want it for only the video

Sort array key and values pair with key ending with digits using Javascript/D3.js

I thought I had this figured out but I was wrong. I’m experiencing a strange issue with sorting the key string ending with a number/digit. When I sort my data to display from highest (newest item added) to the lowest (oldest item added); it seems to sort the key string with the single numbers on top as a group, then the multiple digit numbers will underneath the single numbers. When a new location is added (new one or adding another existing location the array returns random sequence results; not adhering to the sort order, from newest to the oldest. I tried many sort methods, it will sorts but I get the same results mentioned. Below is the code I’m using to show the different location and its number of time it’s listed.

My data array from the console. I am fetching the data from a SharePoint list.

Array(16) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
​
0: Object { key: "Location-9", values: 1 }
​
1: Object { key: "Location-8", values: 5 }
​
2: Object { key: "Location-7", values: 5 }
​
3: Object { key: "Location-6", values: 5 }
​
4: Object { key: "Location-5", values: 14 }
​
5: Object { key: "Location-4", values: 10 }
​
6: Object { key: "Location-3", values: 8 }
​
7: Object { key: "Location-2", values: 6 }
​
8: Object { key: "Location-16", values: 5 }
​
9: Object { key: "Location-15", values: 2 }
​
10: Object { key: "Location-14", values: 2 }
​
11: Object { key: "Location-13", values: 2 }
​
12: Object { key: "Location-12", values: 2 }
​
13: Object { key: "Location-11", values: 2 }
​
14: Object { key: "Location-10", values: 2 }
​
15: Object { key: "Location-1", values: 15 }

My script for counting the number of times the Location was added to the SharePoint list:

data = chartData;

data.sort(function (a, b) { return b.key < a.key ? -1 : 1;})

var LocationCount  = d3.nest().key(function(d) { return d.value; })
  .rollup(function(v) { return v.length; })
  .entries(data);