The items repeat itself in a dynamic multiple slide carousel using Angular

I have a Issue with the carousel that I am creating because the items are repeated after changing the size of the screen. My code base comes from the answer given by Eliseo in this Stackoverflow question where his carousel has the functionality to show/hide the arrow functions after changing the variable noCarousel based on the dimensions of the user’s screen and the amount of items to show, this functionality presents the detail that after hiding the arrows the items are doubled and/or tripled

Code in Stackblitz:

https://stackblitz.com/edit/angular-1vnbxc-zc9fz8?file=src/app/app.component.html

Steps to recreate the Issue (2 ways):

  1. If when opening the code in Stackblitz the carousel has the functionality of the active arrows, expand the sample screen until the arrows disappear.
  2. If when opening the code in Stackblitz the carousel has the inactive arrows functionality, collapse the sample screen until the arrows are activated and then expand it until the arrows disappear.

Image Sample

Expose method creating a web-component using Vue3

I am creating a web-component using VueJS 3, I want to expose a method on the component allowing the user to do something like this:

  <custom-component id="x1" />

  <script>
    var component = document.getElementById("x1");
    
    component.customMethod(); // as focus() method on native elements
  </script>

If I define a method on the component, I can call the method inside the component. But the method is not available when I use it as a web-component.

  //main.ts/js
  import { defineCustomElement } from "vue"
  import component from "./component.ce.vue"

  const element = defineCustomElement(component );

  customElements.define("custom-component ", element);
  //component.ce.vue
  const customMethod = () => { console.log("Exected"); }

How I can indicate to Vue Component Wrapper that the customMethod will be available outside the component?

how do I create a Modal CSS that will work with this JS code

Not sure how to create model for this codes of java script. need to display a list with saved names and then be able to select favorute

function showFavorites() {
    favoritesList = JSON.parse(localStorage.getItem("saveData"));
    fetch(favoritesList[0].url)
      .then(response => response.json())
      .then(data => {
        console.log(data);
      });
  }

        
  function saveFavorites(item) {
    var flag = false;
    for (let i = 0; i < savedLaunches.length; i++) {
      if (savedLaunches[i].url == item.url) {
        flag = true;
      }
    }
    if (flag) {
      return;
    }
    savedLaunches.push(item);
    localStorage.setItem("saveData",JSON.stringify(savedLaunches));
  }

transfer/get json to javascript rest api from rest controller

to me need integrate javascript rest api with app on spring-boot, rest api gets json and making URL. How to call a method in a rest controller in javascript and get json? Help me please

Controller:

@RestController
@RequestMapping("/api/v1/vk-pay")
public class VKPayController {

    private final PaymentService paymentService;

    @Autowired
    public VKPayController(@Qualifier("VKPayServiceImpl") PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @GetMapping("/{id}")
    private Parameters getParams(@PathVariable("id") Long orderId,
                             @AuthenticationPrincipal UserDetails user){
        VKPayPayment payment = paymentService.createOrder("captureUrl", orderId);
        paymentService.save(payment,user.getUsername(),orderId);
        return payment.getParam();
    }
}

javascript:

params = how to get json from restcontroller?
VK.App.open('vkpay', '''params''');

Typescript: How can I extract the value from JSON objects inside an array with changing property names?

I’m new to typescript and would like to extract the value from JSON objects inside an array with changing property names.

My (simplified) code is as follows:

const data = [
              { names: { "1,2": "Matthew" },
              { names: { "2,3": "Marcus", "3,4": "Bill" }},
              { names: { "4,5": "Joana", "5,6": "Bob" }
             ];

const key = "1,2";

const name = data[0].names[key]; // Results in an error message (see below)
const name = data[0].names["1,2"]; // Works but not dynamic

My goal is to extract each value (e.g. “Matthew”, “Marcus”, etc.).

However, I get the following error message:

Type ‘{ names: { “1,2”: string; “2,3”?: undefined; “3,4”?: undefined; “4,5”?: undefined; “5,6”?: undefined; }; }’ is not assignable to type ‘string’

How can I solve this error?

Thanks a lot for your help!

Paste rich text as plain text without HTML markup formatting in Trix editor

I am using Rich Text (Trix editor) with Rails and I want to be able to convert everything that user pastes to sanitized plain text instead of having formatted elements.
Based on Trix documentation I am using this code to convert pasted elements to string.

  element.addEventListener("trix-paste", function(e) {
    element.editor.getDocument().toString()
    console.log(element.editor.getDocument().toString())
  })

In console, it shows correct plain text, but in the editor, all the elements are still formatted.

How can I replace text in the editor to this sanitized text?

Why it doesn’t draw the exponential curve in canvas?

I’m learning the basics of javascript at school, now I’m working on the canvas

This is my code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Funzioni Geometriche</title>

</head>
<body onload="draw()">
    <canvas height="800" width="800" id="myCanvas"></canvas>

    <script src="script.js"></script>
</body>
</html>
canvas = document.getElementById("myCanvas")
ctx = canvas.getContext("2d")
offset = canvas.width/2

function assi(){
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.beginPath()
    ctx.moveTo(offset, 0)
    ctx.lineTo(offset, offset*2)
    ctx.moveTo(0, offset)
    ctx.lineTo(offset*2, offset)
    ctx.stroke()
}

function f(x){
    return Math.pow(2, x)*-1;
}

function draw() {
    assi()
    ctx.beginPath()
    ctx.strokeStyle = "red"

    moveTo(offset, f(0)+offset)
    for (let x = -offset; x < offset; x++) {
        ctx.lineTo(x+offset, f(x)+offset)
    }
    ctx.stroke()
}

This is my question
why in the function f(x) if I leave *-1 it doesn’t draw anything, while if I delete *-1 it draws something?
It draws linear functions, but the exponential function gives problem, and is not Math.pow() the problem, because if I use 1 as base it works (actually draws a line, but is right)

The *-1 is needed to mirror the y-axis of canvas axis system (up to down) into cartesian axis system (down to up)

How do I make this function a number? [duplicate]

I’m learning JavaScript and I wanted to accept user input and add a number to it ,but instead of outputting 12+12 = 24 it’s outputting 12+ 12 = 1212.

document.getElementById("mybutton").onclick = function(){
  var myAge = document.getElementById("mytext").value + 12;
  document.getElementById("value").innerHTML = myAge;
}

I tried doing:
myName = Number(myName)
but it didn’t work

Javascript Menu : Click on to extend & Click off to shorten

I created a menu for a web project, but I have a problem with the javascript side. I would like to extend the div container if it’s clicked. And vice versa, I would like to shorten it if I click everywhere except on it. Actually, the program is able to shorten and extend the div menu but I can’t manage the events :

  • if div is small -> extend it by clicking on it
  • if div is big -> shorten it by clicking everywhere except on it

There is my program :

const menu = document.querySelector('.wrapper')
    const offClick = () => {
        menu.classList.toggle('active')
        document.removeEventListener('click', offClick)
    }
    const handleClick = (e) => {
        e.stopPropagation()
        menu.classList.toggle('.active')
        if (menu.classList.contains('.active')){
            document.addEventListener('click', offClick)
        }
    }
menu.addEventListener('click', handleClick)
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 body{
   display: flex;
   justify-content: center;
   align-items: center;
   min-height: 100vh;
   background-color: #10131c;

 }

 .wrapper{
   position: absolute;
   width: 105px;
   height: 105px;
   background-color: #212532;
   border-radius: 10px;
   cursor: pointer;
   display: flex;
   justify-content: center;
   align-items: center;
   transition: 0.5s;
   transition-delay: 0.8s;

 }

 .wrapper.active{
  width: 300px;
  height: 300px;
  transition-delay: 0s;
 }

 .wrapper span{
   position: absolute;
   width: 10.5px;
   height: 10.5px;
   display: flex;
   justify-content: center;
   align-items: center;
   background-color: #fff;
   border-radius: 50%;
   transform: translate(calc(18px * var(--x)), calc(18px * var(--y)));
   transition: transform 0.5s, width 0.5s, height 0.5s;
   background-color: 0.5s;
   transition-delay: calc(0.1s * var(--i));
 }

 .wrapper.active span{
  width: 67.5px;
  height: 67.5px;
  background-color: #333849;
  transform: translate(calc(90px * var(--x)), calc(90px * var(--y)))

 }

 .wrapper span ion-icon{
  transition: 0.5s;
  font-size: 0em
}

.wrapper.active span ion-icon{
  font-size: 2.025em;
  color: #fff;
}

.wrapper.active span:hover ion-icon{
  color: #d33d32;
  filter: drop-shadow(0 0 3px #d33d32) 

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSite</title>
    <link rel="stylesheet" href="styles/style.css" type="text/css">
</head>
<body class="body">
    <div class="wrapper">
        <span style = "--i:0;--x:-1;--y:0;"><ion-icon name="code-outline"></ion-icon></span>
        <span style = "--i:1;--x:1;--y:0;"><ion-icon name="moon-outline"></ion-icon></span>
        <span style = "--i:2;--x:0;--y:-1;"><ion-icon name="bulb-outline"></ion-icon></span>
        <span style = "--i:3;--x:0;--y:1;"><ion-icon name="chatbubbles-outline"></ion-icon></span>
        <span style = "--i:4;--x:1;--y:1;"><ion-icon name="duplicate-outline"></ion-icon></span>
        <span style = "--i:5;--x:-1;--y:-1;"><ion-icon name="duplicate-outline"></ion-icon></span>
        <span style = "--i:6;--x:0;--y:0;"><ion-icon name="ribbon-outline"></ion-icon></ion-icon></span>
        <span style = "--i:7;--x:-1;--y:1;"><ion-icon name="rocket-outline"></ion-icon></span>
        <span style = "--i:8;--x:1;--y:-1;"><ion-icon name="stats-chart-outline"></ion-icon></span>
    </div>
    
    <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>
    <script src="script/script.js"></script>
</body>
</html>

Thank you for your help !

Next.js keeps throwing error params is undefined

I have successfully connected my custom server using Node.js and Express.js with Next.js. I’m trying to fetch a car by its id whenever I click it among other cars, so I can have that particular car only. But I keep getting an error saying params is undefined even though I get the id at the back of my link whenever I click on the single car in the browser. I’ve tried fetching the data using thunder client and everything works fine. I believe something is wrong with my frontend logic.

This is where I’m trying to fetch the data with the id

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


import Layout from "@/components/Layout";
import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import Authorization from "@/HOC/Authorization";
import axios from "axios";

const Car = () => {
  const [data, setData] = useState("");

  const oneCar = async (params) => {
    const { id } = params;

    const res = await axios.get(`http://localhost:5000/one-car/${id}`);

    setData(res.data);
    if (res.status !== 200) {
      console.log(res.status);
    }
  };

  useEffect(() => {
    oneCar();
  }, []);

  return (
    <Layout>
      {data && (
        <div className="flex flex-col w-11/12 mx-auto mt-8 justify-center bg-blue-200 rounded-lg shadow">
          <div className="flex w-full justify-center mt-6 px-4 mx-auto box-shadow-lg  h-2/4 relative">
            <Image
              src="/assets/images/d17.jpg"
              alt="shopping image"
              className="mx-auto flex rounded-lg inset-0 w-full h-2/4 object-cover"
              width={1000}
              height={500}
            />
          </div>
          <form className="flex-auto p-6">
            <div className="flex flex-wrap">
              <h1 className="flex-auto text-xl font-semibold text-gray-800">
                {data.carName}
              </h1>
              <div className="text-xl font-semibold text-gray-700 ">
                {data.carPrice}
              </div>
              <div className="w-full flex-none text-sm font-medium text-gray-500  mt-2">
                In stock
              </div>
            </div>
            <div className="flex items-baseline mt-4 mb-6 text-gray-800 ">
              <Link
                href="#"
                className="ml-auto hidden md:block text-sm text-gray-500  underline"
              >
                Size Guide
              </Link>
            </div>
            <div className="flex mb-4 text-sm font-medium">
              <button
                type="button"
                className="py-2 px-4  bg-blue-700 hover:bg-blue-800 focus:ring-indigo-500 focus:ring-offset-indigo-200 text-white w-full sm:w-1/4 transition ease-in duration-200 text-center text-base font-semibold shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 mx-auto rounded-lg "
              >
                Buy now
              </button>
            </div>
            <p className="text-sm text-gray-500 text-center ">
              Free shipping on all continental US orders.
            </p>
          </form>
        </div>
      )}
    </Layout>
  );
};

export default Authorization(Car);

This is where I fetch all cars and makes the id a parameter to the link address

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import Image from "next/image";
import Layout from "@/components/Layout";
import Pagination from "@/components/Pagination";
import { GiBinoculars } from "react-icons/gi";
import { useGetAllCarsQuery } from "@/store/ReduxStore/getAllCarsApi";
import Link from "next/link";

const Market = () => {
//I use RTK Query to fetch the data, and It was successfully fetched
  const { data, isLoading, error } = useGetAllCarsQuery();


  return (
    <Layout>
      <div className="2xl:container 2xl:mx-auto">
        <div className=" py-3 lg:px-20 md:px-6 px-4">
          <div className=" flex justify-center mt-3 items-center">
            <div className=" flex space-x-3 justify-center items-center">
              <span className="bg-blue-800 px-4 py-2 rounded-md text-2xl text-white">
                <GiBinoculars />
              </span>
              <input
                type="search"
                className="border-b-2 w-9/12 border-gray-700 -mb-3 leading-5 text-lg p-2 focus:outline-none"
                placeholder="Search for cars here..."
              />
            </div>
          </div>
          <hr className=" w-full bg-gray-200 my-6" />

          <div className=" grid lg:grid-cols-4 sm:grid-cols-2 grid-cols-1 lg:gap-y-12 lg:gap-x-8 sm:gap-y-10 sm:gap-x-6 gap-y-6 lg:mt-12 mt-10">
            {data?.map((cars, i) => (
              <Link
                key={i}
                href="/[id]"
                as={`${cars._id}`}
//I insert the id here
                className="relative"
                passHref
              >
                <div>
                  <div className=" relative group">
                    <div className="caroverlay"></div>
                    <Image
                      width={600}
                      height={400}
                      className="rounded-md w-full"
                      src="/assets/images/d17.jpg"
                      alt="A girl Posing Img"
                    />
                    <div className=" absolute bottom-0 p-8 w-full opacity-0 group-hover:opacity-100 z-20">
                      <button className="text-base font-bold leading-4 text-gray-600 hover:bg-gray-300 hover:text-gray-700 bg-white py-3 w-full">
                        Add to your garage
                      </button>
                      <button className=" bg-transparent  text-base font-bold leading-4 border-2 hover:bg-gray-300 hover:text-gray-700 border-white py-3 w-full mt-2 text-white">
                        View Car
                      </button>
                    </div>
                  </div>

                  <p className="  text-xl leading-5 text-gray-600 md:mt-6 mt-4">
                    {cars.carName}
                  </p>
                  <p className=" font-semibold text-xl leading-5 text-gray-800 mt-4">
                    <span>$</span> {cars.carPrice}
                  </p>
                </div>
              </Link>
            ))}
          </div>

          {/* _______________________________________________________ */}

          <Pagination />

          {/* _______________________________________________________ */}
        </div>
      </div>
    </Layout>
  );
};

export default Market;

Here is my backend logic

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

const router = require("express").Router();
const auth = require("../../middleware/auth");
const Car = require("../../Model/CarSchema");

router.get("/onecar/:id", auth, async (req, res) => {
  try {
    const car = await Car.findById(req.params.id);
    res.status(200).json(car);
  } catch (err) {
    res.status(500).json({ msg: "Server Error" });
  }
});

module.exports = router;

What would be a use case for immediately invoked functions in JavaScript? [duplicate]

If we define a function

(function(){ 
  console.log("");
})();

then it is invoked immediately.
We could define the same function

function foo(){ 
  console.log("");
}
foo();

I fail to see a good use case for this, but if there is one, then I don’t see why we not just define a normal function and call it. Why should we use immediately invoked functions and what are their advantages?