How do I resolve a “firebase is not defined” error? I’m trying to set up Firebase at the most basic level

I’ve been trying to set up Firebase and I’ve got it as simple as I can, just connecting the JS and HTML to the Firebase platform. I’ve tried following the docs and a few YouTube videos and I always get one of these errors:

index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

Access to script at file:/****/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

or

Uncaught ReferenceError: Firebase is not defined

This is my code —

js:

import { initializeApp } from 'firebase/app';
import { firebaseConfig } from "./config";
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';


const firebaseConfig = {
    apiKey: "AIzaSyAF2hE7OOb8VL_13LE2BYNB5FuaVA8nhyM",
    authDomain: "tutorbuddy-685a6.firebaseapp.com",
    projectId: "tutorbuddy-685a6",
    storageBucket: "tutorbuddy-685a6.appspot.com",
    messagingSenderId: "346614475073",
    appId: "1:346614475073:web:15b31c9f954e0ac7e419c0",
    measurementId: "G-S8NRED65K0"
  };
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const firestore = getFirestore(app);

html:

<!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>Document</title>


    <script type="module" src="index.js"></script>

      <script src = "index.js" defer></script>
    
</head>
<body>
    
</body>
</html>

I’ve got npm and firebase installed as well, I’d be happy to provide more info if needed

The answer is probably ridiculously simple but I’ve been at it for a few hours now haha any help would be really appreciated!!

How do I access the value of state within a redux store in javascript?

I am trying to use Grid.js to create a table of data in a Flask app I am building. Grid.js has a checkbox plugin which uses the Redux architecture so that each selection instance keeps the list of selected rows within a Store.

I am following the example code located here: https://gridjs.io/docs/plugins/selection/selection-events

My code can be seen below:

grid.on('ready', () => {
          // find the plugin with the give plugin ID
          const checkboxPlugin = grid.config.plugin.get('selectRow');
          // read the selected rows from the plugin's store
          checkboxPlugin.props.store.on('updated', function (state) {
            console.log('checkbox updated', state);
          });
        });
      </script>

<form method="POST" action="{{ url_for('about') }}">
  <button name="activity" class="btn btn-danger" type="submit" value={{state}}></button> 
</form>

When I select a checkbox the console.log displays the information I want to access in the console. However I do not know how to assign it to a variable so that I can then use a button to send it back to my Flask app in python using a POST form.

Any help would be greatly appreciated.

This is a screenshot of my table, checkbox and value of ‘state’ which can be seen in the console

Error in updating profile with image using mongoose and cloudinary

 updateProfile: async function(req, res) {
    try {
        const update = req.body;
        const id = req.params.id;

        if (!req.files || Object.keys(req.files).length === 0) {
            return res.status(400).send('No files were uploaded.');
        }


        const image = req.files.profileImage;

        const cloudFile = await upload(image.tempFilePath);
        const profileImage = cloudFile.url

        console.log('Loging cloudfile', profileImage)

        await User.updateOne(id, { update }, { profileImage }, { new: true },
            function(err, doc) {
                if (err) {
                    console.log(err)
                }
                if (doc) {
                    return res.status(200).send({ sucess: true, msg: 'Profile updated successful' })
                }
            });

    } catch (error) {
        res.status(500).json({ msg: error.message });
    }

}

But I’m getting an error of "Callback must be a function, got [object Object]"

I have tried to $set: update and $set: profileImage but still not working.

So the image successful upload into the cloudinary but the update for mongoose is not working.

pagination with dots in React using Javascript

I am building pagination where I want to display ‘…’ at certain points. The amount of pages is dictated by user selection; there are 650-ish posts, and users can choose to display 15, 25, 50, or 100 items at a time. Anyway, let’s say that there are 45 pages.
If I am on page one, I want it to look like this:

1 2 3 … 45

if I am on page 3, I want it to look like this:

1 … 2 3 4 … 45

if I am on page 44 (or 45), I want it to look like this:

1… 43 44 45

I am doing this all with JS, I’m not using any extra pagination packages from React. Currently, I have some functionality but I am getting stumped on how to adjust my for loop.

So, right now, if I am on page 1, it looks like :

1 2 … 43 44 45

If I’m on page 3 :

1 2 3 4 … 43 44 45

If I am on page 4:

1… 3 4 5 … 43 44 45

**If I am on page 45:

1 … 44 45

I looked around for a long time, and finally found a stackoverflow thread that helped. I implemented the basic while loop provided by derpirscher.

let pagination = [], i = 1;

 while (i <= totalPageCount) {

   if (i <= 1 || 
     i >= totalPageCount - 2|| 
     i >= currentPage - 1 && i <= currentPage + 1) { 
     pagination.push(i);
     i++;
   } else {
     pagination.push('...');

     //jump to the next page to be linked in the navigation
     i = i < currentPage ? currentPage - 1 : totalPageCount - 2;
   }
 }

In this example, totalPageCount is how many pages there are total, and currentPage is the page the user is currently on. I tried to incorporate some sibling logic where if, for example, the left sibling index was greater than two, I inserted dots. That just resulted in there being dots on the left side of just about every page number, and I definitely didn’t want that.

If it is important, I map through pagination directly in my render function to generate the template.


      {pagination.map((pageNumber) => {

        return (
          <li key={pageNumber}>

            <button
              onClick={() => onPageChange(pageNumber)}
            >
              {pageNumber}
            </button>

          </li>
        )
      })}

Any thoughts or useful resources on this would be appreciated. I know my JS could be better, which is partly why I am trying to practice doing it this way!

Uploading an image, frontend and backend

const { timeStamp, time } = require('console');
const express = require('express');
const fileUpload = require('express-fileupload');
const path = require("path");
const util = require('util');
const app = express();
const port = 3000;

app.use(express.json());
app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/images', express.static(__dirname + 'public/images'))
app.use('/js', express.static(__dirname + 'public/js'))
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());

app.use(express.static("./public"));

app.post("/upload", async (req, res) => {
  try {
    // File name, size and type values
    const file = req.files.file;
    const fileName = file.name;
    const size = file.data.length;
    const extension = path.extname(fileName);
    const name = file;
  
    // Allowed filetypes
    const allowedExtensions = /png|jpg|dds|ico|mov|mp4|flv|avchd|avi|webm|mp3|aac|wav|flac|svg|webp|gif|bmp|tiff|psd|psb|blend|fbx|obj|raw|aep|prel|prproj|ai/;
  
    // Mazimun file Size
    if (!allowedExtensions.test(extension)) throw "Filetype not allowed"
    if (size > 200000000) throw "File must be less than 200MB"

    // Uploaded file name
    const md5 = file.md5;
    const URL = "/uploads/" + fileName + Date.now() + extension;

    await util.promisify(file.mv)("./public" + URL);

    // Errors and Success messages
    res.json ({
      message: "File uploaded successfully!",
      url: URL,
    })

  } catch(err){
    console.log(err);
    res.status(500).json({
      message: err,
    })
  }
})

app.listen(port, () => console.info(`Listening on port ${port}`))


So I have this script for uploading images to a folder in my public folder in the root directory of my website, I’m a real noob when it comes to js so, I was wondering how do I implement a button that let’s the user select a file as well as a submit button and maybe perhaps a couple of text fields where the user can add info about the file in the frontend so it works in the backend?

Because I have no idea of how to make the frontend and backend work together in such a way.

Thanks for any help

need help limiting query to search API from openlibrary.com

I am learning JS, and I am struggeling with this API request. The search API from Openlibrary returns an array of ISBNs, about 400 per book and its slowing down the response time. How can I structure the request so I only get the first result?

This is what I tried:

axios.get(http://openlibrary.org/search.json?title=${query} &limit=100 &fields=isbn[0])

Searching for 0 index isn’t working and their schema at https://github.com/internetarchive/openlibrary/blob/master/conf/solr/conf/managed-schema#L136-L216 didnt help too much either.

Not able to change element attrributes through js [duplicate]

I’ve been closed twice and sent another question but it is not helpful, I checked through it and I stil can’t see what’s wrong so pls don’t close it.

I’m not exactly sure what is wrong, but I can’t seem to implement the functionalities I made in js into my HTML. The only thing from my js that affects the HTML file is my prompt, which loads the prompt with my message, but even from this I can’t seem to make the user input from it change anything, I’m not exactly sure why this is happening so help’s appreciated!

const btn1 = document.getElementsById("1");
const btn2 = document.getElementsById("2");
const btn3 = document.getElementsById("3");
const btn4 = document.getElementsById("4");
const btn5 = document.getElementsById("5");
const btn6 = document.getElementsById("6");
const btn7 = document.getElementsById("7");
const btn8 = document.getElementsById("8");
const btn9 = document.getElementsById("9");
const btn10 = document.getElementsById("10");
const btn11 = document.getElementsById("11");
const btn12 = document.getElementsById("12");
const reset = document.getElementsById("reset");
const pic = document.getElementById("risco");
const bloco = document.getElementById("invbloco");
const valor = 0;

function nivStress()
{
    let num = prompt("Niveis de stress: 3-6");

    if(num = 4){
        bloco.className="bloco";
        btn10.className="butao";
    }
    if(num = 5){
        bloco.className="bloco";
        btn10.className="butao";
        btn11.className="butao";
    }
    else if(num = 6){
        bloco.className="bloco";
        btn10.className="butao";
        btn11.className="butao";
        btn12.className="butao";
    }

}


reset.addEventListener('click', function OnClick(){
    valor = 0;
    pic.src = "risco-nulo.jpg";
    pic.border = "2px solid green";
});

btn1.addEventListener('click', function OnClick(){
    btn1.style.backgroundColor = 'red;';
});

btn2.addEventListener('click', function OnClick(){
    btn2.style.backgroundColor = 'red';
    valor += 3;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn3.addEventListener('click', function OnClick(){
    btn3.style.backgroundColor = 'red';
    valor +=6;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn4.addEventListener('click', function OnClick(){
    btn4.style.backgroundColor = 'red';
});

btn5.addEventListener('click', function OnClick(){
    btn5.style.backgroundColor = 'red';
    valor +=5;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn6.addEventListener('click', function OnClick(){
    btn6.style.backgroundColor = 'red';
    valor += 9;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn9.addEventListener('click', function OnClick(){
    btn9.style.backgroundColor = 'red';
    valor += 4;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn10.addEventListener('click', function OnClick(){
    btn10.style.backgroundColor = 'red';
    valor += 6;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn11.addEventListener('click', function OnClick(){
    btn9.style.backgroundColor = 'red';
    valor += 8;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

btn12.addEventListener('click', function OnClick(){
    btn9.style.backgroundColor = 'red';
    valor += 10;
    if(valor<6){
        pic.src = "risco-nulo.jpg";
        pic.border = "2px solid green";
    }
    else if(valor>= 6 && valor<13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid orange";
    }
    else if(valor >=13){
        pic.src = "risco-moderado.jpg";
        pic.border = "2px solid red";
    }
});

<!DOCTYPE html>
<html>
    <head>
        <title>Risco Cardiovascular</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="risco.css">
        <script src="risco.js"></script>
    </head>
    <body onload="nivStress()">
        <div id="container">
            <h1 id="titulo">Cálculo do Risco Cardiovascular</h1><br>
            <button id="reset" onclick="reset()">Reiniciar</button>
            <h2 class="parametro">Idade</h2>
            <hr class="separador"></hl>
            <div class="block">
                <button class="butao" id="1">&lt;30</button>
                <button class="butao" id="2">&lt;60</button>
                <button class="butao" id="3">&ge;60</button>
            </div>
            <h2 class="parametro">IMC</h2>
            <hr class="separador"></hl>
            <div class="block">
                <button class="butao" id="4">&lt;25</button>
                <button class="butao" id="5">&lt;40</button>
                <button class="butao" id="6">&ge;40</button>
            </div>
            <h2 class="parametro">Stress</h2>
            <hr class="separador"></hl>
            <div class="block">
                <button class="butao" id="7">Nível 1</button>
                <button class="butao" id="8">Nível 2</button>
                <button class="butao" id="9">Nível 3</button>
            </div>
            <div class="invblock">
                <button class="invbutao" id="10">Nível 4</button>
                <button class="invbutao" id="11">Nível 5</button>
                <button class="invbutao" id="12">Nível 6</button>
            </div><br>
            <img id="risco" src="risco-nulo.jpg">
        </div>
    </body>
</html>

#titulo{
    font-size: 20px;
    color: black;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    text-align: center;
    margin:auto;
}

#reset{
    background-color: black;
    color: white;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    text-align: center;
    margin-top: 10px;
    margin-bottom: 10px;
    margin-left: 195px;
    margin-right: 100px;
    width: 100px;
    height: 25px;
}

#container{
    margin: auto;
    width:fit-content;
    height: fit-content;
    margin-top:50px;
    border: 2px solid grey;
    padding: 10px;

}

.parametro{
    text-align: center;
    font-size: 10px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    color: black;
}

.butao{
background-color: grey;
color: white;
font-family: Verdana, Geneva, Tahoma, sans-serif;
width: 150px;
height: 50px;
border:grey;
margin: 5px;;
}

#risco{
    margin:auto;
    border: 5px solid grey;
    display:block;
}

.separador{
    width: 100%;
    color:grey;
}

.block{
    display:inline-block;
    margin: auto;
    margin-bottom: 10px;
}

.invbutao{
    margin: 0px;
    width: 0px;
    height: 0px;
    visibility: hidden;
}

.invblock{
    display:inline-block;
    margin: 0;
    visibility: hidden;
}

How to remove 000webhost watermark with javascript

A few days ago I wanted to host a site with 000webhost, and I noticed that with the free subscription it leaves a watermark on the bottom right corner of the site:

Watermark Image

Watermark code string

I checked with chrome devtools and I noticed that the watermark had no classes , IDs or attribute and therefore I could not simply remove it with CSS with a few lines like that:

 .className{
    display:none
}

then I made a small script in javascript to remove the watermark for anyone who has encountered the same problem:

<script>
    // Code used to remove the 000webhost watermark
    window.onload = _ => {
        let allChildBody = document.body.getElementsByTagName('div'); 
        (allChildBody[(allChildBody.length)-1]).remove();
    }
</script>

How to exclude certain element from checks

Hey guys i have a table that consist of some rows and columns where one of the columns can be empty so i want to exclude it somehow.

Currently i am checking like this which looks like there is to much not needed writings

  cy.get('tr td.cdk-cell.amount.cdk-column-Amount').each(($column) => {
    expect($column).to.not.be.empty
 })

 cy.get('tr td.cdk-cell.cryptocurrency.cdk-column-BTC').each(($column) => {
  expect($column).to.not.be.empty
})
cy.get('tr td.cdk-cell.status.cdk-column-Status').each(($column) => {
  expect($column).to.not.be.empty
})

I cannot do the following since one of the columns always empty

cy.get('tbody[role="rowgroup"] tr td').each(($ele) => {
  expect($ele.text().trim().length).to.be.at.least(1)
})

So my question is how to ignore 1 column and check if all others have value present

Why does my javascript code not register the button clicks? [duplicate]

I am trying to program a Rock Paper Scissors Game but I have some trouble with the JavaScript.

I tested if the code is linked correctly to the html file but alert(“test”); executes just fine.
Therefore I think that the problem must be with the code itself…

I’m new to JavaScript so I am not quite sure what I need to change.
I believe that the order of the code is fine and I don’t really know what the issue with the click event listeners might be.

For reference, here are my html and css files.

<!DOCTYPE html>
<html  lang="en">
<head>
    <title>Rock Paper Scissor</title>
    <link rel="stylesheet" href="./css/style.css">
    <script type="text/javascript" src="./javaScript/doThings.js"></script>
</head>
<body>
    <div class="container">
        <header>
        </header>
        <main>
            <div class="gameButtons">
                <button class="rock"></button>
                <button class="scissor"></button>
                <button class="paper"></button>
            </div>
            <div class="info">   
                    <div class="PlayerCounter">Player: 0</div>
                    <div class="ComputerCounter">Computer: 0</div>
                    <p class="WinLossTie">Win?</p>
            </div>
            <div class="reset"><button class="btnreset"><p id="text">Reset?</p></button></div>
        </main>
    </div>
</body>
</html>

And the css file:

header{
    background: url(../images/rock-paper-scissors-cartoon-banner-with-human-hands-playing-game-showing-fingers-gestures-friends-challenge-competition-decision-strategy-win-people-playing-fun-vector-illustration_107791-8480.webp) no-repeat center center;
    min-height:300px;
    max-height: 500px;
}

main{
    display:flex;
    flex-direction:column;
    margin-top:50px;
}

.gameButtons{
    display:flex;
    justify-content: center;
    gap:25px;
}

.reset{
    margin-top:20px;
    display:flex;
    justify-content: center;
}

.info{
    margin-top: 20px;
    display:flex;
    justify-content: center;
    align-items: center;
    gap: 80px;
}

button{
    border-radius: 25px;
    width:200px;
    height:200px;
    border-color:grey;
}
.reset .btnreset{
    width:100px;
    height:100px;
}

.rock{
    background: url(../images/pexels-luis-quintero-2258250.jpg);
    background-size: 200px 200px;
}

.scissor{
    background: url(../images/pexels-nikolaos-dimou-1319460.jpg);
    background-size: 200px 200px;
}

.paper{
    background: url(../images/pexels-lisa-2304253.jpg);
    background-size: 200px 200px;
}
.container{
    display:flex;
    flex-direction: column;
}

And lastly the JavaScript file:

let player_counter = 0;
let computer_counter = 0;
let player_input = 0;

const btnRock = document.querySelector('rock');
const btnScissor = document.querySelector('scissor');
const btnPaper = document.querySelector('paper');
const btnReset = document.querySelector('btnreset');
let WinLossTie = document.querySelector('WinLossTie');

//register button click and:
function player_choose_value(){
    //check which button has been clicked -> rock 1, scissor 2 or paper 3
    btnRock.addEventListener("click", () =>{
        this.player_input = 1;
    });
    this.btnScissor.addEventListener("click", () =>{
        this.player_input = 2;
    });
    this.btnPaper.addEventListener("click", () =>{
        this.player_input = 3;
    });
}

//generate random value between 1 and 3 and return it
function computer_choose_value(){
    return Math.floor(Math.random()* (3 - 1 +1) + 1);//1 -> rock, 2 -> scissor, 3 -> paper
}

//register button click and:
function reset(){
    this.btnReset.addEventListener("click", () =>{
        this.computer_counter = 0;
        this.player_counter = 0;
        this.player_input = 0;
    });
}

//check if tie or some kind of win, update counters and output field accordingly
function won_tie_lost(){
    //if tie -> "It's a tie!"
    if((player_input == 1 && computer_choose_value == 1) || (player_input == 2 && computer_choose_value == 2)  || (player_input == 3 && computer_choose_value == 3))
    {
        this.WinLossTie.textContent="It's a tie!";
    }
    //rock scissor, computer win
    if(player_input == 2 && computer_choose_value == 1)
    {
        this.WinLossTie.textContent="Rock beats scissor, win for computer";
        this.computer_counter++;
        document.getElementByClassName("ComputerCounter").textContent="Computer: ${computer_counter}";
    }
    //rock scissor, player win
    if(player_input == 1 && computer_choose_value == 2)
    {
        this.WinLossTie.textContent="Rock beats scissor, win for player";
        this.player_counter++;
        document.getElementByClassName("PlayerCounter").textContent="Player: ${player}";
    }
    //rock paper, comupter win
    if(player_input==1 && computer_choose_value==3)
    {
        this.WinLossTie.textContent="Paper beats rock, win for computer"
        this.computer_counter++;
        document.getElementByClassName("ComputerCounter").textContent="Computer: ${computer_counter}";
    }
    //rock paper, player win
    if(player_input==3 && computer_choose_value==1)
    {
        this.WinLossTie.textContent="Paper beats rock, win for player";
        this.player_counter++;
        document.getElementByClassName("PlayerCounter").textContent="Player: ${player}";
    }
    //paper scissor, computer win
    if(player_input==2 && computer_choose_value==3)
    {
        this.WinLossTietextContent="Scissor beats paper, win for computer"
        this.computer_counter++;
        document.getElementByClassName("ComputerCounter").textContent="Computer: ${computer_counter}";
    }
    //paper scissor, player win
    {
        this.WinLossTie.textContent="Scissor beats paper, win for player";
        this.player_counter++;
        document.getElementByClassName("PlayerCounter").textContent="Player: ${player}";
    }
    
}
//put together functions to play a round:
function play_round(){
    player_choose_value();
    won_tie_lost();
}

function won_five_rounds(){
    if(player_counter == 5)
    {
        this.WinLossTie.textContent="Mankind dominates!";
    }
    else if(computer_counter == 5)
    {
        this.WinLossTie.textContent="Mankind sucks!";
    }
}

function game(){//put together game logic:

    while(player_counter!=5 && computer_counter!=5)//while neither has 5 wins:
    {
        play_round();
        won_five_rounds();
    }
}

If there are any resources you think I should read to be able to solve this on my own, please recommend them! I would love to learn.

How do I get a website to display in the body of my reactjs app?

I created a site that I hosted on the web, now I would like to create a button that allows the user to access this site directly in my reactjs application without having to be redirected to another page in my navigator. For this I wrote the following code:

<Button
        component={NavLink}
        activeClassName={classes.activeBtn}
        to="/searchEngine"
        className={classes.buttonItemMiddle}
      >
        {location.pathname == '/searchEngine' ? (
          <Home fontSize="large" style={{ color: 'rgb(0,133,243)' }} />
        ) : (
          <HomeOutlined fontSize="large" />
        )}
      </Button> 

and I inserted this code in my App.js file:

<Route path='/searchEngine' component={() => { 
                          window.location.replace('https://gkwhelps.herokuapp.com'); 
                          return null;
                          }}/>

It did create a button but whenever I click on it I automatically quit my reactjs app and get redirected to the other site. Yet what I would like is for my site to be wrapped in my reactjs application. I have uploaded the solution on some stack overflow questions and on this blog but without success.

Nesting API calls in React/JavaScript maybe call 2nd api call in map()

I have a tricky question in React. I was able to make an API call to get the movies but now I need to make an API call with just the ID of one movie to get the rest of the information.

I’m tempted to make an API call inside the map() function as it will return to me unique information. If I try to make a separate call on its own with the fetchMovieInfo, it will update all the movies with the same information.

I feel the solution is to make another API inside the map() function.

You could see in the comment I was trying to call an API based on a button, but as I said, it updated all the cards with the same information.

Any help is greatly appreciated as I’m almost there…

import { useState } from "react";

const Home = () => {
  const key = 'eee0805f';
  const baseUrl = 'https://www.omdbapi.com/?apikey=' + key;
 
  // This is the search input
  const [message, setMessage] = useState('');
  const [searchTerm , setSearchTerm] = useState('');
  const [movies, setMovies] = useState(null);
  const [movieInfo, setMovieInfo] = useState(null);

  const handleChange = event => {
    setMessage(event.target.value);
  };

  const fetchData = async (url) => {
    try {
        const response = await fetch(url);
        const json = await response.json();
        const newMovies = json.Search;
        setMovies(newMovies);
    } catch (error) {
        console.log("error", error);
    }
  };

  const fetchMovieInfo = async (url) => {
    try {
        const response = await fetch(url);
        const json = await response.json();
        const newInfo = json;
        setMovieInfo(newInfo);
    } catch (error) {
        console.log("error", error);
    }
  };

  const searchMovie = () => {
    let url = baseUrl + '&s=' + encodeURIComponent(message);
    console.log(url);
    fetchData(url);

    setSearchTerm(message);
    setMessage("");
  }

  const moreInfo = (e) => {
    let url = baseUrl + '&i=' + e.target.getAttribute('data-key');
    console.log(url);
    fetchMovieInfo(url);

  }

  // console.log(movies);
  console.log(movieInfo);

  return (
    <div className="home">
      <div className="searchContainer">
        <input type="text" id="message" name="message" onChange={handleChange} value={message} placeholder="Please Enter Movie" />
        <span style={{ 
          color: 'white', 
          backgroundColor: '#f1356d',
          borderRadius: '8px' ,
          padding: '2px 8px'
        }} onClick={searchMovie}>Search</span>
      </div>

      <h3>Title Searched: {searchTerm}</h3>

      {movies && <div>
        {movies.map(movie => (
          <div className="movie-preview" key={movie.imdbID} >
            <div className="movie-content">
              <div className="movie-premier-image-content">
                <img className="movie-preview-image" src={movie.Poster} />
              </div>
              <div>
                <h2 className="movie-preview-headline">{ movie.Title }</h2>
                <p>{movie.Year}</p>

                  {/* The problem here is that the information is all the same.  */}
                  {movieInfo && <div>
                    <p>Director(s): {movieInfo.Director}</p>
                    <p>Genre: { movieInfo.Genre }</p>
                    <p>Date released: {movieInfo.Released}</p>
                  </div>}


              </div>
            </div>

            {/* <div style={{ 
              color: 'white', 
              backgroundColor: '#f1356d',
              borderRadius: '8px' ,
              padding: '2px 8px',
              height: '24px',
              width: '75px'
              }} onClick={moreInfo} data-key={movie.imdbID}>More Info</div> */}
          </div>
        ))}


      </div>}



    </div>
  );
}
 
export default Home;

Parcel build outputs javascript boilerplate for each html file

I am experimenting with building a website with vanilla HTML, CSS and JS.

I am using Parcel for bundling. When I run parcel build index.html, it is generating a boilerplate javascript file for each of the html files in the project, despite there not being a single piece of javascript written or imported anywhere in these files.

The build output doesn’t show that these files were generated:
enter image description here

However they still appear in the output directory:
enter image description here

How can I stop Parcel from generating these JS files?

JavaScript doesnt see my id from getElementById

I have home page with 24 divs, I made a function that will hide all other divs except one that I put in function, but I’m getting error. So I have function choice and inside event listener, so if user click on cruiseHoliday div all other divs except backpacking should dissapear. All code is provided, if you need something more I’m here, I just cant find a mistake

HTML:

   <div class="row">

    <!--main divs-->
    <div style="background-color: #4cc9f0" class="column" id="adventureHolidays"><p>Adventure Holidays</p></div>
    <div style="background-color: #4895ef" class="column" id="backpacking"><p>Backpacking</p></div>
    <div style="background-color: #4361ee" class="column" id="cruiseHolidays"><p>Cruise Holidays</p></div>
    <div style="background-color: #4361ee" class="column" id="eventTravel"><p>Event Travel</p>
    </div>
    <div style="background-color: #3a0ca3" class="column" id="packageHoliday"><p>Package Holiday</p></div>
    <div style="background-color: #480ca8" class="column" id="safari"><p>Safari</p></div>
    <div style="background-color: #560bad" class="column" id="skiingAndSnowboarding"><p>Skiing and Snowboarding</p>
    </div>
    <div style="background-color: #7209b7" class="column" id="volunteering"><p>Volunteering</p></div>

    <!--end on main divs-->

    <!--sub divs-->

    <div style="background-color: #4cc9f0" class="column" id="aH-summerCamps"><p>Summer camps</p></div>
    <div style="background-color: #4895ef" class="column" id="aH-trekking"><p>Trekking</p></div>
    <div style="background-color: #4361ee" class="column" id="bP-longDistanceHiking"><p>Long Distance Hiking</p></div>
    <div style="background-color: #4361ee" class="column" id="bP-thruHiking"><p>Thru Hiking</p></div>
    <div style="background-color: #3a0ca3" class="column" id="c-oceanCruising"><p>Ocean Cruising</p></div>
    <div style="background-color: #480ca8" class="column" id="c-riverCruising"><p>River Cruising</p></div>
    <div style="background-color: #560bad" class="column" id="e-recreationsEvent"><p>Recreations Events</p></div>
    <div style="background-color: #7209b7" class="column" id="e-sportsEvents"><p>Sports events</p></div>
    <div style="background-color: #4cc9f0" class="column" id="pH-escortedTours"><p>Escorted Tours</p></div>
    <div style="background-color: #4895ef" class="column" id="pH-independentTours"><p>Independent Tours</p></div>
    <div style="background-color: #4361ee" class="column" id="s-photographicSafari"><p>Photographic Safari</p></div>
    <div style="background-color: #4895ef" class="column" id="s-cyclingSafari"><p>Cycling Safari</p></div>
    <div style="background-color: #3a0ca3" class="column" id="sAs-backcountrySkiing"><p>Backcountry skiing</p></div>
    <div style="background-color: #560bad" class="column" id="sAs-downhillSkiing"><p>Downhill skiing</p></div>
    <div style="background-color: #4361ee" class="column" id="v-childcare"><p>Childcare</p></div>
    <div style="background-color: #4895ef" class="column" id="v-conservationAndEnvironment"><p>Conservation And
        Environment</p></div>

</div>

<script type="text/javascript" th:src="@{/js/index.js}"></script>

JS:

    let adventureHolidays = document.getElementById("adventureHolidays");
let backpacking = document.getElementById("backpacking");
let cruiseHolidays = document.getElementById("cruiseHolidays");
let eventTravel = document.getElementById("eventTravel");
let packageHoliday = document.getElementById("packageHoliday");
let safari = document.getElementById("safari");
let skiingAndSnowboarding = document.getElementById("skiingAndSnowboarding");
let volunteering = document.getElementById("volunteering");
/*End of inserting main variables*/

/*sub variables*/

let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bPLongDistanceHiking = document.getElementById("bP-longDistanceHiking");
let bPThruHiking = document.getElementById("bP-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");

/*end of subs variables*/

const divs = ["adventureHolidays", "backpacking", "cruiseHolidays", "eventTravel", "packageHoliday", "safari", "skiingAndSnowboarding", "volunteering", "aH-summerCamps", "aH-trekking", "bP-longDistanceHiking", "bP-thruHiking", "c-oceanCruising", "c-riverCruising", "e-recreationsEvent", "e-sportsEvents", "ph-escortedTours", "ph-independentTours", "s-photographicSafari", "s-cyclingSafari", "sAs-backcountrySkiing", "v-conservationAndEnvironment", "sAs-downhillSkiing", "v-childcare"]
    .map(id => document.getElementById(id)); // gives you an array of those elements


function hideAllDivsExcept(id) {
    for (const div of divs) div.hidden = !div.id === id;
}


window.onload = function () {
    choice();
};


/* start of function choice for user clicks*/

function choice() {
    cruiseHolidays.addEventListener("click", () => {
        hideAllDivsExcept('backpacking');
        console.log("Backpacking");
    })
}

Error:

index.js:39 Uncaught TypeError: Cannot read properties of null (reading 'id')
at hideAllDivsExcept (index.js:39:47)
at HTMLDivElement.<anonymous> (index.js:52:9)

function hideAllDivsExcept(ids) {
here is error >  for (const div of divs) div.hidden = !div.id === ids;
}

jQuery – Call click event on dinamiclly created button in loop

I have html table which i populate with content via ajax and php.
I dinamiclly generate table rows and last column is row need to contain link/button where i need to call action for deliting that item (eg.Product) from table row.

I dont have idea how to call that specific ID becouse all is happening in loop each. Only in loop i have information about product id but in loop to call click() event not work and is so dumb for me. I think there is better solution to do that.

Check my code:

$.ajax({
            url: '/admin/dokument/5/edit?ajax',
            type: 'GET',
            success: function(response) {
                 
                response = $.parseJSON(response);

                $.each(response, function(i, item) {
                    i++;
                    var $tr = $('<tr>').append(
                        $('<td>').text(i),
                        $('<td>').text(item.id),
                        $('<td>').text(item.name),
                        $('<td>').text(item.qty),
                        $('<td>').text(item.jm),
                        $('<td>').text(item.price),
                        $('<td>').text(item.discount),
                        $('<td>').text(item.pdv),
                        $('<td>').text(item.total),

                        <!-- this is for delete -->

                        $('<td class="text-center">').html('<button type="button" id="product_'+item.id+'" class="btn btn-sm"><i class="fa fa-remove"></i></button>'),

                        
                        // This not work inside loop
                        $("#product_"+item.id).click(function(e) {
                            alert(item.id);
                        }),

                    ).appendTo('#document_items_table > tbody');
                 });

             },
              complete: function(){
                $loading.hide();
              }

 

Do you have any idea how to execute this for specific product? Thanks!