Uncaught (in promise) ReferenceError: getNFTNames is not defined

I am not so familiar with javascript, and i’m using someone else’s code, and added some new functions with parameters, and it’s throwing the following error

It’s somehow not recognizing the functions with parameters.

Uncaught (in promise) ReferenceError: getNFTNames is not defined
window.App = {
 start: function() {
  var self = this;

  Voting.setProvider(web3.currentProvider);
  NFTContract.setProvider(web3.currentProvider);
  self.populateNFTs();
 },

populateNFTs: function() {
  var self = this;
  NFTContract.deployed().then(function(contractInstance) {
    contractInstance.allNFTs.call().then(function(NFTArray) {
      for(let i=0; i < NFTArray.length; i++) {
        NFTs[NFTArray[i]] = "tokenID-" + i;
      }
      console.log("NFT Array = " + JSON.stringify(NFTs));
      self.setupNFTRows();
    })
  })
 },

 setupNFTRows: function() {
  Object.keys(NFTs).forEach(function (NFTid) { 
    $("#NFT-rows").append(
      `<tr id='NFT_ID_${NFTid}'>
          <td>NFT_ID_${NFTid}</td>
          <td>${this.getNFTNames(NFTid)}</td>
          <td>${this.getCreators(NFTid)}</td>
         </tr>`);
  });
},

getNFTNames:function (nftid){
  NFTContract.deployed().then(function(contractInstance) {
    contractInstance.getNFTname.call(nftid).then(function(v) {
      return v.toString();
    });
  });
}

}

Installing Node.js Using JavaScript Code? [closed]

I’ve been programming for decades but am new to JavaScript.

I recently began working on a new project which I want to be able to run
on Linux, Windows and Apple. After some research I decided to use HTML
and JavaScript. I was thinking/hoping I would be able to do the entire
project using only client-side coding, but it doesn’t appear like that’s
going to be the case.

I’ve encountered a point where I need to copy/move files from one location
to another.

What are my options? Node.js?

If Node.js is my only or best option, is it possible to download and
install Node.js using client-side JavaScript code? (Many of the people
who will be using the system will be computer-challenged and/or elderly.
It may be daunting for them if they need to install Node.js themselves.)

I appreciate any help.

How to write a JS function that is used by .html files in different folders?

I’m trying to call a function on my XAMPP server that dynamically changes the current stylesheet of an HTML document. This is what I’m currently doing:

document.getElementById("color-scheme").href = "../colors.css";

The colors.css is obviously one folder above the page that is using this code, hence the “../”. Now my problem is that there are dozens of pages in different folder levels that all need to access this colors.css to set the color-scheme. For example:

  • index.php (same folder)
  • news/index.php (one folder in)
  • news/january/index.php (two folders in)
    … and so on.

This means that every page that isn’t exactly one folder above colors.css doesn’t work as it can’t find the file at “../colors.css”, as the server seems to go back beyond the root to find the file.

I feel like manually adding “../” according to the folder’s level would be very bad coding, so I don’t want to do this:

function LoadColorScheme(var level) {
   var path = "";
   for (var i = 0; i < level; i++) 
      path += "../";
   path += "colors.css";
 }

Is there a better way to do this?

How to iterate through an object with key and get the value

So I am not sure why I having such a difficult time with this, but I have an object I am trying to map over to get a value from it.

For example:

let obj = {
      "lyzjmpkvbtocygakcoxu": {
        "label": "Show Time",
        "hour": "12",
        "minute": "00",
        "period": "p.m.",
        "add_time": "enabled",
        "bdlmynfythqgyzrhruhw_add_date": "December 01, 2021",
        "bdlmynfythqgyzrhruhw_stock": ""
      },
      "eueuuzvkteliefbnwlii": {
        "label": "Show Time",
        "hour": "05",
        "minute": "00",
        "period": "p.m.",
        "add_time": "enabled",
        "brtmypzvuooqhvqugjbj_add_date": "December 02, 2021",
        "brtmypzvuooqhvqugjbj_stock": ""
      }
    }

I want to be able to get this:

December 01, 2021, December 02, 2021

I was able to do this to get the values and key for “add_time”, however what I want is values for key containing the “…_add_date”.

Object.keys(obj).reduce(
          (acc, elem) => {
            acc[elem] = obj[elem].add_time;
            return acc;
          },
          {},
        );

How to get data from another page html using the same script.js?

I’m really struggling with this, I’m using fetch to get data from rest api countries, and displaying some countries in index.html. My case is that when I click on a country, I want to move to detail.html and display more data from the country I clicked on. I don’t know how to deal with this. I tried to use the same script.js in detail.html and hoped to get the e.target from the addEventListener, but the code collided as a result. It would be much easier if I created a modal in index.html, but instead of doing that I want to move to a different page and get my skills increased a bit. Should I use a backend in this case?

If you’d like to see the preview site or the codes here are the links site, code

React Redux Image Wont load

So this could honestly be as simple as just over looking it and staring for so long and being new to react but on my section component I’m loading in my backgroundImg prop wont load the image and I cant figure it out. My pictures are in the public folder and my code is in the src components folder

Also, I can get images to load in the file just not when I’m calling them through prop

Home.js This is where I am calling my component and trying to load the file in through the prop type

import React from 'react'
import styled from 'styled-components'
import Section from './Section'


function Home() {
    return (
        <Container>
            <Section 
                title="Model S"
                description="Order Online for Touchless Delivery"
                backgroundImg='/public/pictures/model-s.jpg'
                leftBtnText="Custom Order"
                rightBtnText="Existing Inventory"
            />
            <Section 
                title="Model E"
                description="Order Online for Touchless Delivery"
                backgroundImg=".Picturesmodel-e.jpg"
                leftBtnText="Custom Order"
                rightBtnText="Existing Inventory"
            />
            <Section />
            <Section />
            
        </Container>
    )
}

export default Home

//Home and styled help you stlye the component without using css

const Container = styled.div`
    height: 100vh;
`


Section.js The component for the Screen

import React from 'react'
import styled from 'styled-components'


//props are just parameters you can set when calling the component

function Section(props) {
    
    return (
        <Wrap bgImg={props.backgroundImg}>
            <ItemText>
                <h1>{props.title}</h1>
                <p>{props.description}</p>
            </ItemText>
            <Buttons>
                <ButtonGroup>
                    <LeftButton>
                        {props.leftBtnText}
                    </LeftButton>
                    <RightButton>
                        {props.rightBtnText}
                    </RightButton>
                </ButtonGroup>
                <DownArrow src='/Pictures/down-arrow.svg' />
            </Buttons>
        </Wrap>
    )
}

export default Section

const Wrap = styled.div`
    width: 100vw;
    height: 100vh;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
`

const ItemText = styled.div`
    padding-top: 15vh;
    text-align: center;
`

const ButtonGroup = styled.div`
    display: flex;
    margin-bottom: 30px;
    @media (max-width: 786px){
        flex-direction: column;
    }
`

const LeftButton = styled.div`
    background-color: rgba(23, 26, 32, 0.8);
    height: 40px;
    width: 256px;
    color: white;
    display: flex; 
    justify-content: center;
    align-items: center;
    border-radius: 100px;
    opacity: 0.85;
    text-transform: uppercase;
    font-size: 12px;
    cursor: pointer;
    margin: 8px;
`

const RightButton = styled(LeftButton)`
    background: white;
    opacity: 0.65;
    color: black;
`

const DownArrow = styled.img`
    margin-top: 20px;
    height: 40px;
    overflow-x: hidden;
    animation: animateDown infinite 1.5s;
`

const Buttons = styled.div`

`


Thanks for the help.


javascript sum of json objects

After trying to find many ways to do it here, I’m stuck with this.

I have a Json object and would like to sum all the results.
This code is showing all amounts, but not showing their sum in the end.

var str = e.data.substring(e.data.indexOf("["));
    if (IsJsonString(str)) {
        var body = JSON.parse(str);
        var data = body[1];

        if(data && data.id == "ID" && data.some.string == "string"){

            var fields= [
                data.some
              ];
              var sum = fields.reduce(function(acc, val){
                return (+acc.amount) + (+val.amount);
              }, {amount: 0});
              console.log(sum);
        }
    }

moment js need help hiding the booked time

I am working on creating an appointment application using momentjs and I don’t want to show the time that is already booked. I was able to do using a while loop but I have to pass by the index number for each time. Is there a shortcut way to do this if the bookedTime is more than 2? This is what I have so far. Any help will be appreciated:

const get24HoursTimeWithInterval = (
  interval = 30,
  startHour = 0,
  endHour = 24,
  bookedTime = [],
  timeToPrepareForNextWork = 0,
) => {
  const startTime = moment(startHour, 'h:mm A');
  const endTime = moment(endHour, 'h:mm A');
  const bookedBeginTime = moment(bookedTime[0], 'h:mm A');
  const bookedEndTime = moment(bookedTime[1], 'h:mm A');

  if (endTime.isBefore(startTime)) {
    endTime.add(1, 'day');
  }
  const timeStops = [];
  if (bookedTime.length > 0) {
    while (startTime < bookedBeginTime) {
      timeStops.push(new moment(startTime).format('h:mm A'));
      startTime.add(interval + timeToPrepareForNextWork, 'minutes');
    }
    while (bookedEndTime < endTime) {
      timeStops.push(new moment(bookedEndTime).format('h:mm A'));
      bookedEndTime.add(interval + timeToPrepareForNextWork, 'minutes');
    }
  } else {
    while (startTime <= endTime) {
      timeStops.push(new moment(startTime).format('h:mm A'));
      startTime.add(interval + timeToPrepareForNextWork, 'minutes');
    }
  }
  const slots = timeStops;

  return slots;
};
console.log(get24HoursTimeWithInterval(30, 0, 24,['12: 00 PM', '1:00 PM', '1:30 PM', '2:30 PM'], 10))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

How to compare values while looping over multiple arrays simultaneously in javscript? [closed]

First off, I know this question has been asked before but it dosent seem to match my case.

I was a doing a coding assement and had a question like this:
enter image description here

I need to loop over two arrays simultaneously and compare their values to a number. I could not figure out how to do this.

  1. Is it possible to do this with for loops?

  2. Why was my code not hitting the 3 on the outer loop?

  3. What is the optimal solution considering time and space complexity?

Arguments Object

i’m currently learning js and need to pass a test, every requirement checks out besides “should work on an arguments object”. I noticed that when I take out the Array.isArray() part of the code, it works. However then I wont pass the “return an empty array if array is not an array” part of the test.

we are allowed to ask for help on stackoverflow so I would appreciate the help. thanks 🙂

this is my code:

// Return an array with the first n elements of an array.
// If n is not provided return an array with just the first element.
_.first = function (array, n) {
  var resultArray = [];
  if (Array.isArray(arguments[0]) !== true){
    return []} 
  else if (arguments[1] > arguments[0].length){
  return arguments[0]
 } else if (typeof arguments[1] !== "number" || arguments[1] == 0 || arguments[1] < 0){
  resultArray.push.call(resultArray, arguments[0][0])
  return resultArray
 } else {
 for (var i = 0; i < arguments[1]; i++)
 resultArray.push.call(resultArray, arguments[0][i]);
 return resultArray;
}
};

html adding a comma to user inputs on a form

I have a html form taking user inputs as per below. However, when the form submits, I get the data in the back-end in the below format. Notice that the make, model, and engine capacity data has a comma and brackets yet the other fields are okey. I really do not know why this is the case. Anyone help me fix this.

Description             Details Provided
MAKE:                    ('MAZDA',)
MODEL:                   ('ATENZA',)
TRIM DETAILS:             standard
ENGINE CAPACITY (cc):     (2000,)
FUEL TYPE:                PETROL
MILEAGE (km):             120000
TRANSMISSION:             AUTOMATIC
YEAR OF MANUFACTURE:      2009

Prevent active accordion item from closing on click

i’m working on a design for a site, but i’m super new to any kind of coding, so there’s a lot that i don’t know the answer to (and haven’t been able to find yet).

currently, i’d like to know if it’s possible, with the code i currently have, to prevent the active accordion item/panel from closing when the header is clicked.

here’s the relevant part of my current code:

var acc = document.getElementsByClassName("accordionHeader");
var panel = document.getElementsByClassName('accPanel');

for (var i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    var setClasses = !this.classList.contains('open');
    setClass(acc, 'open', 'remove');
    setClass(panel, 'open', 'remove');
    if (setClasses) {
      this.classList.toggle("open");
      this.nextElementSibling.classList.toggle("open");
    }
  }
}

function setClass(els, className, fnName) {
  for (var i = 0; i < els.length; i++) {
    els[i].classList[fnName](className);
  }
}
document.getElementById("defaultOpen").click();
.accordionHeader {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}

.accPanel {
  padding: 0 18px;
  background-color: white;
  display: none;
  overflow: hidden;
  transition: max-height 0.5s ease-out;
}

.open {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <title>polka time</title>
</head>

<body>
  <div>
    <button class="accordionHeader" id="defaultOpen">section 1</button>
    <div class="accPanel">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
      animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda
      est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
    </div>

    <button class="accordionHeader">section 2</button>
    <div class="accPanel">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
      animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda
      est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
    </div>
    <button class="accordionHeader">section 3</button>
    <div class="accPanel">
      At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia
      animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda
      est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis
      voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
    </div>
  </div>

  <script src="character page js.js" type="text/javascript"></script>
</body>

</html>

if at all possible i’d like to not change too much about the code, since i only just got it working (more or less). i’m sure my code’s a total mess though since i’ve mainly been copying off tutorials the whole time.

also if there’s a good way to get the accordion to animate that would be a bonus.

How to run an async function in js with timeouts (for rate limiting)

I’m designing a system where a user will interact with my RESTful API through JS, and will replace the ts html element with a different SVG if the returned answer is true. If the API call returns false, the JS should wait for 5 seconds, before retrying the API call. again, if the API call returns true, the SVG will be changed, and the function will stop calling the API. How can I have the function “sleep” for 5 seconds before running again, and ending the function if the returned API call is true?

Code:

async function getTransaction(){
var lookup = $("meta[name='lookup']").attr("content");  
axios.get('http://127.0.0.1:5000/client_api/transaction_status/' + lookup) 
.then(function (response) {
    var tStat = response.data.transactionStatus;
    console
    if(tStat){
      document.getElementById("ts").innerHTML = 'drawing the new svg and replacing the old one'
      console.log('transaction_found')
    }
    else if(!tStat){
      console.log("transaction not found")
    }
    else{
      console.log("error")
    }
  });
  }console.log("hello"); while(true){setTimeout(getTransaction,5000);}

javascript: backgroundColor not working on a element

im trying to change the background color of this <li> element but I’m getting error Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor'). i have been trying to fix this for hours but nothing works. As you can see, I want it to change the background color of the rows element in an if statement and below is my JS code.

var vals;
var rows;
var sum;
var rowsarr = [];
var avg;

function obser1() {
    const trades = document.querySelector('.scrollbar-dark');
    const observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.addedNodes.length) {
                vals = [...mutation.addedNodes[0].querySelectorAll("span")].map(span => span.textContent);
                if (vals.length == 4) {
                    rows = vals[2];
                    rowsarr.push(rows);
                }
                if (vals.length == 3) {
                    rows = vals[1];
                    rowsarr.push(rows);
                }
                console.log(mutation.addedNodes[0]);
                console.log(rows+"  rows");
            }
        })
        function arraysum(x, y) {
            return parseFloat(x) + parseFloat(y);
        }
        sum = rowsarr.reduce(arraysum);
        console.log(rowsarr.length + "  length");
        if (rowsarr.length >= 100 && rowsarr.length<105) {
            avg = sum / 50;
            console.log("average is  " + avg);
        }
        /*This is the problem*/
        if (rows > avg) {
            console.log(rows + "  large" + "  average  " + avg);

            rows.style.backgroundColor = "white";
        }
    });
    observer.observe(trades, {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true
    })
   
}

window.setTimeout(btn4, 1000);
window.setTimeout(obser1, 1700);