How to turn the elements in a div into an array with js/jQuery

I’m trying to make a list of buttons and their names into an array in javascript?
I heave searched the internet for help but not found anything so far. The div with the name “apps” is where I’m trying to grab from and the array inside of the if statement in the javascript code is what I’m to to replace with the array.

HTML code:

<!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">
    <link rel="stylesheet" type="text/css" href="clicker.css">
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <title>Vairoon's clicker</title>
</head>
<body>
    <button onclick="smnPlayer()">Get new player</button>
    <p>Players per click: <span id="PPC">1</span></p>
    <p>Players: <span id="players">0</span></p>
    <p>New players per second: <span id="PPS">0</span></p>
    <div class="upgrade">
        <p>Upgrade your clicker game: <span id="upgCost">400</span></p>
        <button id="upgrade">Upgrade clicker</button>
    </div>
    <div id="apps" name="apps"> <!-- The div I'm trying to grab from-->
    </div>
    <script ="clicker.js"></script>
</body>
</html>

Javascript code:

var players=0;
var PPS=0;
var PPC=1;
var upgradeCost=400;
var apps = ["New buildings","More upgrades","Adverts","More minigames"]
var basecosts = [0,20,100,1500,15000]
function getEl(elID) {
    return document.getElementById(elID);
}
function smnPlayer() {
    players+=PPC;
    document.getElementById("players").innerHTML=players;
}
getEl("upgrade").onclick = function upgrade() {
    if (players>=upgradeCost) {
        players-=upgradeCost;
        upgradeCost=upgradeCost*3;
        PPC=Math.ceil(PPC*2);
        PPS=PPS*2;
        getEl("players").innerHTML=players;
        getEl("upgCost").innerHTML=upgradeCost;
        getEl("PPC").innerHTML=PPC;
        getEl("PPS").innerHTML=PPS;
    }
}
setInterval(() => {
    if (players>=upgradeCost) {
        getEl("upgrade").style.display="block";
    } else {
        getEl("upgrade").style.display="none";
    }
    for (let index = document.querySelectorAll('#apps').length; index < basecosts.length+1; index++) {
        if (players>=basecosts[index]) {
            if (array.includes(apps[index])){}else{ //the "array" is what to replace with the array
                var button = document.createElement("BUTTON");
                button.innerHTML = apps[index];
                document.getElementById("apps").appendChild(button);
            }
        }
    }
    
},10)

Prototype extension

In my library, how do I extend prototype of Object thus the users of the library would be able to use that extension?

For example, inside my library I do Object.prototype.greet = () => console.log("Hello"). How do I make it possible for the end user of the library to use that method, just like ({}).greet()?

How do I change state on dropdown select in React

for a bit of context I’m trying to make a component navigation menu for my react app. Essentially each dropdown value is equivalent to some components. The way I was going to do this is like follows:

Dropdown menu

<form>
            <label htmlFor="#endpointSelect">Endpoint:</label><br/>
            <select value={moduleValue} id="endpointSelect" onChange={() => activateModuleValue()}>
                <option value="1"> Latest </option>
                <option value="2"> Convert </option>
                <option value="3"> Historical </option>
                <option value="4"> Time Series </option>
                <option value="5"> Fluctuation </option>
                <option value="6"> Carat </option>
                <option value="7"> Lowest-Highest </option>
             </select>
          </form>

And this is the activateModuleValue()

const [module, setModule] = useState();

// set the module value
  const activateModuleValue = () => {

    console.log(moduleValue);

  }

Eventually there will be a method with a bunch of if statements indicating 1 = <Latest/>, 2 = <Convert/>, etc.

What I was having issues with is correctly grabbing the option values. Using onChange in general I’ve noticed it returns the value FROM the element I’m changing from instead of changing TO.

Another approach that I’m currently trying is using the value={moduleValue}. Essentially on dropdown select the moduleValue state should change, and ideally I’d have something along the lines of:

useEffect(() => {
        activateModule();
    }, [moduleValue]);

Where the intent would be to call on the “setActiveComponenet” method whenever the state for moduleValue changes

How to update the style of an element within an element using js

In the javascript below, how would I designate the class btn that exists within the div id = 8?
Also, if I needed to add “!important” to the background color, how would I do that?

html:

<div id="8">
<div class="1">
<div class="2">
<div></div>
<a class="btn">...</a>
</div>
</div>
</div>

js:

$('#8 .btn')[0].style.background = 'white';

Thank you!

How to change the visibility of a div when browser reloads ..?

I want to make the main div hidden when someone hits the refresh button and then after sometime making the main div visible. The reload detection code is working but why the div isn’t getting hidden ..? Please help me solve this any other solutions …?

CSS

#Web_1920__1 {
    position: absolute;
    width: 3554px;
    height: 2346px;
    border: 0px grey solid;
    background-color: rgba(255,255,255,1);
    visibility: visible;
    overflow: visible;
}

JAVASCRIPT

//check for Navigation Timing API support
if (window.performance) 
{
  console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) 
{
  console.info( "This page is reloaded" );
  
  document.getElementById("Web_1920__1").style.visibility = "hidden";

  setInterval(function() 
    { 
        document.getElementById("Web_1920__1").style.visibility = "visible";

    }, 700); 
} 
else 
{
  console.info( "This page is not reloaded");
}

Setting the visibility hidden outside setInterval function not working. How can I fix this ..?

javascript constructor function I made not working

so I tried to make this change name method but as I tried to print it, it instead outputs the age… also in visual studio code it crosses the name after the equal

function person(N, A) {
  this.name = N;
  this.age = A;
  this.changeName = function(nameChange) {
    //The name here↓
    this.name = name;
  }
}

let p1 = new person("Adam", 23);
p1.changeName("Haziq");

document.write(p1.name)

File with .pptx extension is being downloaded without extension

Here is the function:

export const downloadFile = ({
  url,
  content,
  fileName,
  options
})=> {
  const anchor = document.createElement('a');
  const blobUrl = url || URL.createObjectURL(new Blob([content], options));

  anchor.setAttribute('href', blobUrl);
  anchor.setAttribute('download', fileName);
  anchor.click();
};

When I call it with options = { type: 'application/pdf' } it downloads the filename.pdf file, but when the type is application/vnd.openxmlformats-officedocument.presentationml.presentation, it downloads filename without extension, what’s the problem?

Vue3. Use one var in different methods for auth

It mess me up… I’m frustrated.
How to use the ‘validToken’ variable to add it to the auth line for headers? It catches the error message (fetchHeaders func)…

I can’t understand why the ‘axios’ authentification doesn’t work for auth request (returns ‘headers fetched with error!’), but works if I set validToken hardcoded..
It returns me validToken correctly for template…

Pls help!
Thx in advance!

    #App.vue
    
    <script>
    import axios from 'axios';
    const FormData = require('form-data');
    const API_URL = "https://my_api_path.com/"
    let data = new FormData();
    data.append('username', 'my_username');
    data.append('password', 'my_password');
    let config = {
        method: 'post',
        url: `${API_URL}/login`,
        data: data
    }
    let validToken = ""
    
    export default {
        data() {
            return {
                validToken: "",
                headers: []
            }
        },
        methods: {
            async userLogin() {
                try {
                    await axios(config)
                        .then((resp) => {
                        this.validToken = resp.data.access_token;
                        //console.log(JSON.stringify(resp.data.access_token));
                    });
                    Token = this.validToken;
                } catch(err) {
                    console.log(err)
                }
            },
            async fetchHeaders() {
                try {
                    let config = {
                        headers: {
                            Authorization: `Bearer ${validToken}`
                        }
                    }
                    const resp = await axios.get(`${API_URL}/headers/`,
                        config
                    )
                    this.headers = resp.data;
                } catch (err) {
                    console.error("headers fetched with error!");
                }
            }
        },
        mounted() {
            this.userLogin(),
            this.fetchHeaders()
        }
    }
    
    </script>

Unmarshall of string set does not work as expected

I have tried to marshall DynamoDB’s String Set and unmarshall it back as below.

import {marshall, unmarshall} from '@aws-sdk/util-dynamodb';

test('Marshall and Unmarshalling Tests', () => {
  const raw = {
    'anArray': new Set([
      'Apple',
      'Mango'
    ])
  };

  console.log(JSON.stringify(marshall(raw)));
  // {"anArray":{"SS":["Apple","Mango"]}}

  const marshalledResult = marshall(raw);

  console.log(JSON.stringify(unmarshall(marshalledResult)));
  // {"anArray":{}}

});

But I am not able to get the String Set back. How should we be doing this when we should get a String Set from dynamo db and use it?

Fit rect() around text() width

I am using p5.js for something and I need to have text inside rectangles appearing at the top of my canvas. I want this text to force the rect() around it to fit so that there is no empty space of the rectangle, it just wraps around the string.
Previously I tried giving the rectangle dimensions manually, though this worked poorly depending on the length of the string. I have looked at using HTML5’s canvas ‘measureText’ and ‘fillText’ functions, though these work only for the html canvas, not the javascript canvas I have loaded a background image onto.

I want to have the coloured rectangle fit around the text, on the JS canvas as below.
JS background image canvas with rectangle

With the following code:

function word (x) {
this.wordX = x;
this.wordY = random(5,30);

this.display = function(){
    fill('#4545f5');
    rect(this.wordX,this.wordY,420,55);
    fill('#ffffff');
    textSize(25);
    text("alphabet", this.wordX+5, this.wordY+10, 410, 55); 
}

What can I use to make the box fit neatly around the text and still use the JS background canvas, or can I put an image from a file onto the HTML canvas?
Following is the setup() code for instantiation and canvas drawing:

function preload() { 
    BG = loadImage('images/background.PNG'); 
}

function setup() {
    createCanvas(windowWidth,windowHeight);
    word1 = new word(random(10,windowWidth-370));
}

function draw() {
  image(BG, 0, 0, windowWidth, windowHeight);

  word1.display();
}

CORS problem with Access-Control-Allow-Origin in place [duplicate]

I’m sure this is just me doing something wrong because I don’t understand something quite right. We want to have a js library used by several apps in a central store on our server. I don’t want to have to have developed install localhost copies of these. When developing in localhost, the domain is, well, ‘localhost’, and therefore violates CSP and CORS.

I got around the CSP with a Content-Security-Policy header setting in the localhost’s page response. But now, I’m getting CORS violations everytime the library on the server attempts to load a font or image from itself. I’m under the impression that the Access-Control-Allow-Origin header on the load of the page in localhost should fix this. I’ve tried setting it to localhost or to the server’s name, or to *. None of these prevent the CORS complaints. I can’t see how to add both at the same time.

The errors in Chrome’s console look like the below.

Access to font at 'https://dev-afmsag-02/Static/js/ext-6.2.1/build/development/Afms/resources/fonts/OpenSans-Regular.ttf' from origin 'http://localhost:9080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Is it saying, I have to have the Access-Control-Allow-Origin when it requests the ttf and other static resources? Or am i doing something else wrong?

The header (I’ve tried each of the following):

Access-Control-Allow-Origin: http://localhost:9080
Access-Control-Allow-Origin: https://dev-afmsag-02

google-visualization-errors: container is null. message: Container is not defined

Table and Table1I try to use colorFormatter to colour table column but get this error “google-visualization-errors: container is null. message: Container is not defined” and colour does not display out.

       var colorFormatter = new google.visualization.ColorFormat();
       colorFormatter.addRange(0.01, null, 'white', 'red');
       colorFormatter.format(data, 6);  
  
       var Formatter = new google.visualization.ColorFormat();
       Formatter.addRange(0.01, null, 'white', 'red');
       Formatter.format(data, 5); 

Here is using event Listener to draw out the table. Able to get table shown out but unfortunately no red colour highlighted as shown in table1

                              google.visualization.events.addListener(categoryPicker2, 'ready',
                 function(event) {
                    // group the data of the filtered table and set the result in the pie chart.
                    table.setDataTable( google.visualization.data.group(
                    // get the filtered results
                    table1.getDataTable(),
                    [0,2,3],
                    [{'column': 4, 'aggregation': google.visualization.data.avg, 'type': 'number'},{'column': 5, 'aggregation': google.visualization.data.avg, 'type': 'number'},{'column': 6, 'aggregation': google.visualization.data.avg, 'type': 'number'}]
                ));
                    // redraw the pie chart to reflect changes
                                                            table.draw(data,{allowHtml: true});
                });
                
                google.visualization.events.addListener(categoryPicker3, 'statechange',
   
                function(event) {
                    // group the data of the filtered table and set the result in the pie chart.
                    table.setDataTable( google.visualization.data.group(
                    // get the filtered results
                    table1  .getDataTable(),
                    [0,2,3],
                    [{'column': 4, 'aggregation': google.visualization.data.avg, 'type': 'number'},{'column': 5, 'aggregation': google.visualization.data.avg, 'type': 'number'},{'column': 6, 'aggregation': google.visualization.data.avg, 'type': 'number'}]
                ));
                    // redraw the pie chart to reflect changes

                    table.draw(data,{
      allowHtml: true
    });
                });
 
                google.visualization.events.addListener(categoryPicker2, 'statechange',
   
                function(event) {
                    // group the data of the filtered table and set the result in the pie chart.
                    table.setDataTable( google.visualization.data.group(
                    // get the filtered results
                    table1  .getDataTable(),
                    [0,2,3],
                    [{'column': 4, 'aggregation': google.visualization.data.avg, 'type': 'number'},{'column': 5, 'aggregation': google.visualization.data.avg, 'type': 'number'},{'column': 6, 'aggregation': google.visualization.data.avg, 'type': 'number'}]
                ));
                    // redraw the pie chart to reflect changes

                    table.draw(data,{
      allowHtml: true
    });
                });

Passport Js is serializing the user but not deserializing it

Hello Everyone I am Having a tough time in understanding passport JS google-oauth2.0. When I used the following code the user is serialized and a cookie is stored but req.user is undefined. Please help me out.
I have used MongoDB as database

Index.html file

const express = require("express");
const app = express();
var cookieParser = require('cookie-parser');
const passport = require("passport");
const connectDB = require("./Database/database.js");
const PORT = 5000;
var cors = require('cors')
const session = require('express-session');
app.use(express.json());
app.use(cors({credentials: true }));


connectDB(); // Connects the mongoDB database
app.use(cookieParser());
app.use(
  session({
    secret: "secretcode",
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 7, // One Week
    },
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.use("/api/auth", require("./Routes/User")); // Contains the routes for auth

app.listen(PORT, () => {
  console.log("Listening on Port");
});

User.js file which has the routes for authentication

const express = require("express");
const router = express.Router();
const User = require("../Schema/User.js");
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;


require("dotenv").config();



passport.serializeUser(function (user, done) {
  console.log("Serialize function called " + user._id)
  // This function is called and data is logged as well stored in       sessions
  done(null, user._id);
});

passport.deserializeUser(function(id, done) {
  // This function is never called
  User.findById(id, (err, user)=>{
    done(err, user)
  })
});


passport.use(
  new GoogleStrategy(
    {
      clientID: `${process.env.GOOGLE_CLIENT_ID}`,
      clientSecret: `${process.env.GOOGLE_CLIENT_SECRET}`,
      callbackURL: "http://127.0.0.1:5000/api/auth/google/callback",
    },
    function (accessToken, refreshToken, profile, cb) {
        User.findOrCreate({ id: profile.id, email: profile.emails[0].value, name:profile.displayName }, function (err, user) {
        return cb(err, user);
      });
    }
  )
);


router.get("/google", passport.authenticate("google", { scope: ["profile", 'email'] }));

router.get(
  "/google/callback",
  passport.authenticate("google", {
    failureRedirect: "http://127.0.0.1:3000/login",
    session: true,
  }),
  function (req, res) {
    res.redirect("http://127.0.0.1:3000");
  }
);

router.get("/logout", (req, res) => {
  if (req.user) {
    req.logout();
    res.send("Logout Successfull");
  }
});

router.get("/getuser", (req, res) => {
  console.log(req.user) // This is printing undefined
  res.send(req.user);
});

module.exports = router;

I am not able to deserialize the user??Can someone help me?

Delete user endpoint using Fetch

I am building a user website, where the admin should be able to delete users.
My project is build using Azure SQL database.
I have in my controllers file, come up with an endpoint deleteUser

deleteUser

const deleteUser = (req, res) => {
  sql.connect(config, function (err) {
    if (err) console.log(err);
    // create Request object
    var request = new sql.Request();
    // query to the database and get the records

    const { id } = req.query

    request.query(
      `DELETE FROM users where User_ID = '${id}'`,
      function (err, recordset) {
        if (err) {
          console.log(err);
        } else if (!id) {
          res.json("Please provide an ID")
        } else {
          res.json(`User with ID: ${id} has been deleted!`)
        }
      }
    );
  });
};

I am then trying to make a call to this endpoint using fetch and EJS.

My code in EJS script tag

<script>

document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {

    e.preventDefault();

    fetch('http://localhost:3000/deleteUser', {
    method:'DELETE',
    headers: {
        "Content-Type": "application/json",
      },
      body: null
    })
    .then((response) => console.log(response))
    .catch((e) => {
        console.log(e)
    })
})
</script>

I console log the response, so the route must be good, but it seems as it doesn’t parse the ID into the fetch. What is the right way to approach this?

Thanks in advance!