can I open the pdf in current or new tab from html2pdf instead of downloading it (open pop up )

Hi so I created a function using html2pdf, it works fine pdf is generated and can download it with no problem, but now I want the function to open the file directly instead of opening the browser pop up to open/save file

function looks like this:

const download = () => {
    const element = document.getElementById("element-to-print");
    const opt = {
      filename: patientName + "_Report.pdf",
      image: { type: "jpeg", quality: 0.98 },
      html2canvas: { scale: 2 },
      jsPDF: { unit: "in", format: "a4", orientation: "landscape" },
    };

    // New Promise-based usage:
    html2pdf().set(opt).from(element).save();
   
  };

 
    }, []);

const and let fake hoisting in modules

I’ve found interesting behaviour while having let and const on module level.

func.mjs

export const func = () => {
  return num1 + num2;
}

const num1 = 5;
const num2 = 6;

main.mjs

import {func} from 'func.mjs';

console.log(func())

If you run node main.mjs, you’ll get 11 in console. I can explain that as all module level expressions defined and initialised on import step.

But is it falling under concepts of TDZ?

set an input to api parameter after geocoding

I’m currently trying to use an API and i’m new to programming…
my question today is :

  • how to retrieve data from a geocoding adress and how to implement it in another API parameter ?

    var coords = '';
              if (place.address_components) {
                  coords = [
                      (place.geometry.location.lat() && place.geometry.location.lng()||''),].join(' ');
              }
    
    
    
              var Isochrones = new openrouteservice.Isochrones({
                  api_key: 'x'
              });
    
              Isochrones.calculate({
                  profile: 'foot-walking',
                  locations: coords,
    

    here is my code, as you can see i tryed to change the locations parameter by a variable, but i dont know how to get the lat/lng data to implement in it.
    thanks for help or clue.
    Have a nice day.

Invalid array length allocation failed

I have this code:

JavaScript code in an IDE

I’m receiving this error when trying to run my JS:

FATAL ERROR: invalid array length Allocation failed – JavaScript heap out of memory

I’ve checked other similar posts that say to increase the memory size f.x., node --max-old-space-size=16000 yourFile.js or from FATAL ERROR to my script they both don’t work. Any help would be greatly appreciated.

Send a slider variable to php

I have a slider on my html page and I need to pass the input variable (I mean the percentage of slider, so the id) on a php variable in the same page.
I’ve tried many methods, but no one has worked.

I attach my code below. I don’t write here the style tag: ask me for it if you need.

<!DOCTYPE html>
<html>
    <body>
        <div class="container">
            <input type="range" id="my-slider" min="0" max="100" value="50" oninput="slider()">
            <div id="slider-value">0</div>
        </div>
        <script type="text/javascript">
            const mySlider = document.getElementById("my-slider");
            const sliderValue = document.getElementById("slider-value");
            function slider(){
                valPercent = (mySlider.value / mySlider.max)*100;
                mySlider.style.background = `linear-gradient(to right, #3264fe ${valPercent}%, #9c9c9c ${valPercent}%)`;
                sliderValue.textContent = mySlider.value;
            }
            slider();
        </script>
        </body>
</html>

multiple user upload image fields using javascript

so I have an upload image button that works so the user can upload an image from their computer to the website I’m working on and the image shows on the page. I need help figuring out how to make multiple of these image upload fields that allows the user to upload a different image to each field. so far I can only get one to work. heres my code:

<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;">Upload Image</label></p>
<p><img id="output" width="200"></p>

<script>
var loadFile = function(event) {
    var image = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
};
</script>

How can set a shuffle status with array in discord.js (javascript)

I want to set my discord bot’s activity shuffle messages that i have to get from an array.
I’ve tested this code but it will only shows the last one in array or just first and last sometimes :

const aa = [
    { type: 'PLAYING', message: array.type }
];
const presence = aa[Math.floor(Math.random() * aa.length)];
client.user.setActivity(presence.message, { type: presence.type });

And this is my array :

    [
  {
    id: '08933438391',
    type: 'ejx1'
  },
  {
    id: '12361425430',
    type: 'ejx3'
  },
  {
    id: '63746455430',
    type: 'ejx2'
  },
  {
    id: '83972535430',
    type: 'ejx4'
  }
]

Thank you for your helps.

How do I display API data in HTML?

I want to create a site that gives you a random quotation and the author’s name. I’ve fetched the data from the API but I have little experience with Javascript and don’t know how to display the data fetched from the API in the HTML. Thank you in advance.
Here is my code:

const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Host': 'quotes15.p.rapidapi.com',
        'X-RapidAPI-Key': 'd0841880f8msh7096a86c0f2386ep194eb4jsnbd4df5524a07'
    }
};

fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Quotes</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>

</head>
<body>
    <div class="container">
        <div id="content"></div>
        <div id ="author"></div>

    </div>

    </div>
    <script src='main.js'></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</body>
</html>

Bezier gradient function instead of linear – JavaScript

I have made my own gradient generator in JavaScript and it works well. Using it, I made a rectangle that starts black and fades linearly into green. This is what it looks like:

enter image description here

The function finds the distance
between the two inputted numbers,
and then finds the correct number
based on the decimal put in.

// Gradient Function
function linearGradient(a, b, decimal) {
    const dist = b - a
    return a + dist * decimal
}

/* EXAMPLE USE */

// Green & Black colours
const color_black = [0, 0, 0]
const color_green = [0, 255, 0]

// Make a for-Loop to find the Red, Green and Blue values of each stage
const resolution = 20
for (let i = 0; i < resolution; i ++) {
    red = linearGradient(color_black[0], color_green[0], i / resolution)
    green = linearGradient(color_black[1], color_green[1], i / resolution)
    blue = linearGradient(color_black[2], color_green[2], i / resolution)
}

So, to put into graphics, this is what the function does:

enter image description here

That’s alright as it is, but the reason I made this function was for making a smooth or bezier gradient. At the moment this is a linear gradient, as it travels linearly from one point to the next. In graph terms, linear goes in a straight line, but bezier moves by speeding up gradually, reaching an average peak, and then slowing down:

enter image description here

Any thoughts of what can I change in my function to do that? Any help would be appreciated

Javascript – Rectangle collision detection and stop player upon collision

You control a player on a 2d canvas, you can move around using ‘WASD’. I want to create collision with another cube that’s drawn on the screen (using canvas.getContext('2d')), and when you approach it from any side, it will stop the player from moving into that drawn cube (Collision).

I have the X and Y coordinate of the drawn cube, held in an array ‘[]’, this array is called ‘cubeX‘ and the other is ‘cubeY‘.

The player X and Y coordinate is held in a class, you can access this by using ‘player.x‘ or ‘player.y‘

Hide an element only on first load but shows it all the time later

We have a button that hides and shows a section. The section is hidden by default on all viewports on load, so when the button is clicked the section will show.

<button class="hide-show-btn" style="display: block; margin: 0 auto">Customize Mat & Continue</button>
<script>
jQuery(".hide-show-btn").click(function(event) {
    event.preventDefault(); 
    var lable = jQuery(".hide-show-btn").text().trim();
    if(lable == "Customize Mat & Continue") {
        jQuery(".hide-show-btn").text("Hide Customization Window");

        jQuery("#product-options").show();
        //jQuery("#product-options2").show();
    } else {
        jQuery(".hide-show-btn").text("Customize Mat & Continue");
        jQuery("#product-options").hide();
        //jQuery("#product-options2").hide();
    }
});
</script>

The section has some functionality that will refresh the page (A customization form that will refresh the page to update some data), but we want the section to remain visible after the refresh so the user wont need to click on the button to show the section again once that happens.

So we need the section to be hidden when the page first loads(first time) but not if the page is refreshed later in the same session. Is there a way to do this using JavaScript?

Minha classe do arquivo instanciada com valor nulos no navegador fica normal [closed]

Estou com um problema os valores que passo na inicialização da minha classe não chegam ao constructor dentro do arquivo. Porém quando defino os valores pelo console do navegador a classe é iniciada corretamente.

    constructor(mobileMenu, navList, navLinks){
        this.mobileMenu = document.querySelector(mobileMenu);
        this.navList = document.querySelector(navList);
        this.navLinks = document.querySelectorAll(navLinks);
        this.activeClass = "active";
    }
    
  
    addClickEvent() {
        this.mobileMenu.addEventListener("click", () => console.log("teste"));
    }
    init() {
        if (this.mobileMenu) {
            this.addClickEvent()
        }
        return this;
    }
}

const mobile = new MobileNavBar('.mobile-menu','.nav-list','.nav-list li');
mobile.init();

html

        <nav>
            <a href="" class="logo">Responsible menu</a>

            <div class="mobile-menu">
                <div class="line1"></div>
                <div class="line2"></div>
                <div class="line3"></div>
            </div>
            
            <ul class="nav-list ">
                <li><a href="/">Home</a></li>
                <li><a href="/">About</a></li>
                <li><a href="/">Projects</a></li>
                <li><a href="/">Contact</a></li>
            </ul>
        </nav>
    </header>

Aqui tem uma imagem mostrando o teste, a classe mobile que mostro na primeira coluna é a do arquivo, a classe teste é a que instancio com os mesmos valores porém no console.
Teste realizado

Javascript: Get Array of arrays in single array [duplicate]

I am gathering a list of promises in an array and then awaiting all the promises to be fulfilled.

let promises = [];
let infos = [];
let pagesOf5Ids = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]];

pagesOf5Ids.forEach(ids => {
    promises.push(this.serviceClient.getInfoByIds(ids));
});

await Promise.all(promises).then(result => {
    infos = result;
});

What I get in infos is an array of arrays.

[
  [{"id": 1, "name": "JON"}, {"id": 2, "name": "JON"}, {"id": 3, "name": "JON"}, {"id": 4, "name": "JON"}, {"id": 5, "name": "JON"}],
  [{"id": 6, "name": "JON"}, {"id": 7, "name": "JON"}, {"id": 8, "name": "JON"}, {"id": 9, "name": "JON"}, {"id": 10, "name": "JON"}],
  [{"id": 11, "name": "JON"}, {"id": 12, "name": "JON"}, {"id": 13, "name": "JON"}, {"id": 14, "name": "JON"}, {"id": 15, "name": "JON"}]
] 

I require the infos to be an array of objects and not array of arrays. Is there a way to flatten the response?

TypeError: mongoose.model() is not a function in Nextjs with mongoose

I am creating E-commerce app with Nextjs and using Mongoose in that app, in that app
i have this productSchema (models/Product):

const mongoose = require("mongoose");
const productSchema = new mongoose.Schema(
  {
    title: { type: String, required: true },
    slug: { type: String, required: true, unique: true },
    desc: { type: String, required: true },
    category: { type: String, required: true },
    size: { type: String },
    color: { type: String },
    price: { type: Number, required: true },
    title: { type: String, required: true },
    availableQty: { type: Number, required: true },
    img: { type: String, required: true },
  },
  { timestamps: true }
);

export default mongoose.model("Product", productSchema);

This is getProducts api (api/getProducts):

import Product from "../../models/Product";
import connectDb from "../../middleware/mongoose";
const handler = async (req, res) => {
  let products = await Product.find();
  res.status.json({ products });
};

export default connectDb(handler);

This is mongoose.js file (middleware/mongoose):

import mongoose from "mongoose";

const connectDb = (handler) => async (req, res) => {
  if (mongoose.connections[0].readyState) {
    return handler(req, res);
  }
  await mongoose.connect(process.env.MONGO_URI);
  return handler(req, res);
};

export default connectDb;

when i open api/getProducts in the browser , i am gettting the Error :
TypeError: mongoose.model() is not a function.

How can i fix this? what is the issue?