How to detect when window.open fails to open a link

I am building a web app which has a list of links which deeplinks to an already installed application on the user’s phone. But i want to handle a scenario whereby the application is not installed and link the user to the appstore or playstore. I am opening the links with window.open

How to send BUSD with metamask/web3.js

I have two coins in binance testnet:

enter image description here

I can send default main coins (BNB) to another account:

web3.eth.sendTransaction({
   from: account,
   to: '0x64123c0c6cc87a7b96c498D584Db17c6cA55eD6F',
   value: '1000000',
}, function (err, transactionHash) {
                    
});

But i don’t know how to send other coins (USDT or BUSD).

Also i can check current amount of coins, but only for BNB:

const balance = await this.web3.eth.getBalance(account);

How to pass HTML input string value as a JavaScript Function Parameter?

Good evening,

I’m trying to pass an HTML input (a string) value as a JavaScript Function Parameter. I am pretty new to coding and recently started DOM Manipulation.


          function lengthOfPassword (strLength) {
  
            if (strLength.length >= 5) {
              return true; 
            } else {
              return false; 
            };  
            }
            console.log(lengthOfPassword("l"));

This is the original function I wrote, and it performs as needed returning true or false depending on the length.

I have used the onclick="()" and document.getElementById("").value; to take the value from the HTML input and have it run in the function.

This is how far I have got:

<body>
    <label for="password">Password:</label>

    <input id="pwd" type="text" minlength="5" />
    <button id="btn" onclick="lengthOfPassword()" type="button">Submit</button>

    <script src="DOM.js"></script>
  </body>

and my JS function now looks like this:

        
        function lengthOfPassword() {

        let strlength = document.getElementById("pwd").value;
  
          if (strlength.length >= 5) {
            return true; 
          } else {
            return false; 
          };  
          }

I feel like I am tripping at the finish line! If someone could help explain where I have gone wrong, that would be great!

Absolute Imports not working with WebPack

I’m trying to setup up absolute imports, but it seems my webpack configs are wrong and the entry point it starts from is relative and not from ./src

I’ve looked through the webpack docs and they recommend adding an entry point, which I have but still nothing.

structure:

Project
|- src
     | - components 
         | - Home
              | - Featured.tsx
     | - contexts
         | - index.ts
         | - AllDataProvider.tsx
|-package.json
|-tsconfig.json
|-webpack.config.js

    // FEATURED.TSX
import React from 'react';
import {useData} from '../../contexts';  // this works
import {useData} from 'contexts'; // this doesn't work.

Even though when I hover over both the imports they points to the say index.ts file that has all the exports.

// WEBPACK
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  devtool: 'source-map',
  devServer: {
    historyApiFallback: true,
  },
  entry: './src',
  module: {
    rules: [
      {
        test: /.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },
      {
        test: /.svg/,
        use: {
          loader: 'svg-url-loader',
          options: {
            // make all svg images to work in IE
            iesafe: true,
          },
        },
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'index.html',
    }),
    new CopyWebpackPlugin({
      patterns: [
        { from: 'public/_redirects' },
      ],
    }),
  ],

};

//TSCONFIG 

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "baseUrl": "src",
    "paths": {
      "src/*": ["src/*"]
    },
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

Where am i going wrong?

Is there a way to change a div’s children’s styles and then move the children outside of the div while keeping their new style from the parent?

Is there a way to append a group of elements to a div and then change the css style of the div (and therefore also changing the style of the children) and then take the group of elements back out with the new css style it got from the parent div?

First I append all the child elements into the div with:

var target_children = document.getElementsByClassName(ndmove);
    for (let i = 0; i < target_children.length; i++) {
        plane.appendChild(target_children[i]);
    }

(‘plane’ is the id of the div I’m appending the children to).

Then I rotate the plane with:

plane.style.transform = "rotateX(90deg)";

(My program should be able to rotate in all three dimensions).

Finally, I append the children back to the original div (“cube”) with:

let cube = document.getElementById("cube");
        while (plane.firstChild) {
            let target_block = plane.lastChild;
            cube.appendChild(target_block);
        }

The “cube” div is contains all of the children (the “target_children” are only the specific children that I would like to append for that invocation of a function based on its input) and the “plane” div.
Basically:

<div id="cube" class="cube">
    <div id="plane" class="plane"></div>
    <div child></div>
    <div child></div>
    ...
</div>

If there is a better way to rotate the “target_children”, I’m fine to completely restart this project.

THREE.JS Skybox not displayed on screen

I am trying to include a skybox to a scene in a web page, so I followed a tutorial I found, everything seems to work correctly as my console (on firefox) doesn’t display any errors or warning.

First the code creates an array of texture, then assembles the textures in a box and finally adds the box to the scene. I don’t have any light in my scene as every objects are visible without any so far (and when I try to add one it doesn’t change anything, and the console doesn’t show any error either).

I thought it could be a matter of distance of the camera to the skybox so I got the skybox closer to the camera but still nothing.

I put my code down here if you want to see what I did so far. Thanks in advance for your help!

var camera, scene, rendu;
var r, t;

init();

function init() {
    r = 3;
    t = 1.1;
    // ---------- scene et camera --------- //
    camera = new THREE.PerspectiveCamera( 70 , window.innerWidth / window.innerHeight , 0.01 , 2000 );
    camera.position.set( 0 , 0 , 4 );
    camera.lookAt(new THREE.Vector3( 0, 0, 0 ));

    scene = new THREE.Scene();

    loadSkybox();

    // ---------- rendu ------------- //
    rendu = new THREE.WebGLRenderer( { antialias: true} );
    rendu.setSize( window.innerWidth, window.innerHeight );
    rendu.setPixelRatio(window.devicePixelRatio);
    rendu.setAnimationLoop( animation );
    document.body.appendChild( rendu.domElement );

}

function animation() {
    rendu.render( scene, camera );
}


function createPathStrings(filename) {
    const basePath = "./ulukai/";
    const baseFilename = basePath + filename;
    const fileType = ".png";
    const sides = ["ft", "bk", "up", "dn", "rt", "lf"];
    const pathStrings = sides.map(side => {
      return baseFilename + "_" + side + fileType;
    });

    return pathStrings;

}

function createMaterialArray(filename) {
  const skyboxImagepaths = createPathStrings(filename);
  const materialArray = skyboxImagepaths.map(image => {
    let texture = new THREE.TextureLoader().load(image);

    return new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide });
  });

  return materialArray;

}

function loadSkybox() {
    // ----------- skybox -------------- //
    var skyboxImage = "corona";
    skyboxGeo = new THREE.BoxGeometry(1000, 1000, 1000);
    skybox = new THREE.Mesh(skyboxGeo, createMaterialArray(skyboxImage));
    scene.add(skybox);
}

Adding multiple values TXT record on aws ROUTE 53 using nodejs

I am trying to create multi line TXT record on aws rout53 using nodejs. The issue is I am not able to insert the new line. below is the chunk of code.

nike = "verify_sdf5423456tfggg";

  {
     Action: "UPSERT",
       ResourceRecordSet: {
           Name: domain.join("."),
             ResourceRecords: [
                {
                 //here I need a new line after '?all'
                  Value: """ + "v=spf1 include:spf.mandrillapp.com ?all" + """ + "n" + nike
                }
               ],
               TTL: 300,
               Type: "TXT"
             }
          }

The output on TXT record should be like this

"v=spf1 include:spf.mandrillapp.com ?all"
"verify_sdf5423456tfggg"

I have tried various options but not able to do this. Can someone please help me here? TIA

Decimal number grow out of control when using setInterval function

I would like to use setInterval to increase a number by 0.1/s, and I would also like to apply this function multiple times to the number (click once, +0.1/s, click twice, +0.2/s, etc).
However, when I execute the function, the number would increase to something like 3.00000001 instead of 3, or 7.999999999 instead of 8. How do I fix this?

let btn = document.querySelector(".button");
let num = document.getElementById("number");
let increment = 0;
function toAdd() {
  setInterval(() => {
    num.innerHTML = parseFloat(num.innerHTML)+increment;
  }, 1000)
}

btn.addEventListener("click", toAdd, increment+=0.1);
<span id="number">0</span>
<button class="button">
Click to Add
</button>

jQuery input element with id selection using id selector

I am using JQuery 3.6 and I’m trying to create a simple email registration snippet on a page.

I am surprised that when I type an email in the input, and click the button, the alert box shows a blank. I get the same result when I use Code Inspector. The element is identified and selected correctly, but for some reason, I can’t seem to extract the email value entered in the input box.

Here is my markup and minimal Javascript:

<div class="g-mb-30">
    <div class="input-group border-0 rounded">
        <input id="newsletter-subscription-email" class="form-control border-0 g-pa-12" type="email" title="Subscribe to our newsletter!" placeholder="Email address">
        <div class="input-group-append p-0">
            <button id="newsletter-subscribe" class="btn btn-primary" type="submit" role="button">Subscribe</button>
        </div>
    </div>  
</div>

<script type="text/javascript">
function isValidEmail(some_email){
/* impl detail */
}

$()ready(function(){
    $('#newsletter-subscribe').on('click', function(e){
       let email = $('#newsletter-subscription-email').val().trim().toLowerCase();
       alert(email);  // displays blank if even I type an email address

       if (email.length && isValidEmail(email)) {
           e.preventDefault();

           // some logic ...
       }
    }
});
</script>

Why is the address not being correctly retrieved – since the selector CSS is correct – and how do I fix this to correctly retrieve the entered email?

Display selected tab item into url path

I want to display selected tab item into url path. I found this Material UI example:

import * as React from 'react';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`vertical-tabpanel-${index}`}
      aria-labelledby={`vertical-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

function a11yProps(index: number) {
  return {
    id: `vertical-tab-${index}`,
    'aria-controls': `vertical-tabpanel-${index}`,
  };
}

export default function VerticalTabs() {
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  return (
    <Box
      sx={{ flexGrow: 1, bgcolor: 'background.paper', display: 'flex', height: 224 }}
    >
      <Tabs
        orientation="vertical"
        variant="scrollable"
        value={value}
        onChange={handleChange}
        aria-label="Vertical tabs example"
        sx={{ borderRight: 1, borderColor: 'divider' }}
      >
        <Tab label="Item One" {...a11yProps(0)} />
        <Tab label="Item Two" {...a11yProps(1)} />
        <Tab label="Item Three" {...a11yProps(2)} />
        <Tab label="Item Four" {...a11yProps(3)} />
        <Tab label="Item Five" {...a11yProps(4)} />
        <Tab label="Item Six" {...a11yProps(5)} />
        <Tab label="Item Seven" {...a11yProps(6)} />
      </Tabs>
      <TabPanel value={value} index={0}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
      <TabPanel value={value} index={2}>
        Item Three
      </TabPanel>
      <TabPanel value={value} index={3}>
        Item Four
      </TabPanel>
      <TabPanel value={value} index={4}>
        Item Five
      </TabPanel>
      <TabPanel value={value} index={5}>
        Item Six
      </TabPanel>
      <TabPanel value={value} index={6}>
        Item Seven
      </TabPanel>
    </Box>
  );
}

https://mui.com/components/tabs/#VerticalTabs.tsx

Sandbox: https://codesandbox.io/s/verticaltabs-material-demo-forked-yyqhm

I found this code example how to add url param:
https://v5.reactrouter.com/web/example/nesting

Do know how I can implement the code to display selected tab into url link. Example: https://yyqhm.csb.app/<selected_tab>

react-electron global object/class

I’m trying to make a global accessible object, so that its values can be changed and can be read from every component. I’ve create a classs with static fields:

export default class Settings {
  static first: string;

  static second: string;
}

Lets say I have two components in separate files:

import Settings from './Settings'

// located in firstComponent file
export default function FirstComponent() {
Settings.First = 'test'    <---------------- SET VALUE
return (some html)
}

// located in secondComponent file
export default function SecondComponent() {
let qq = Settings.First <----------------------- ASSUME HERE IS VALUE "TEST"
}

But it is not working. How I can create static class/fields that will be accessible within all components like C# static classes. Is it even possible?

Thanks in advance

Looping through multiple collection of arrays

I have a lot of data as response not parsed and also, so you can see what is in the response. But i want all the scores from the table results, the quary fiters on actorId, categoryId, what gets all the data of all subjects from that specific actorId.

parsed data response from the localhost of my:

[
{
"id": 1,
"name": "Word",
"tests": [
{
"id": 1,
"title": "Test  1",
"name": "Test 1",
"description": "This is the description of the first Test",
"totalPoints": 2,
"duration": 30,
"level": 1,
"subjectId": 1,
"questions": [ ],
"paragraphs": [ ],
"results": [
{
"id": 22,
"score": 100.0,
"timeElapsed": 5,
"actorId": 13,
"actor": null,
"testId": 1,
"resultQuestions": [ ],
"resultSliders": [ ]
}
],
"sliders": [ ],
"pausedTests": [ ]
},
{
"id": 5,
"title": "new test",
"name": "new test",
"description": "asdf",
"totalPoints": 0,
"duration": 9,
"level": 3,
"subjectId": 1,
"questions": [ ],
"paragraphs": [ ],
"results": [
{
"id": 19,
"score": 0.0,
"timeElapsed": 4,
"actorId": 13,
"actor": null,
"testId": 5,
"resultQuestions": [ ],
"resultSliders": [ ]
}
],
"sliders": [ ],
"pausedTests": [ ]
},
{
"id": 8,
"title": "test",
"name": "test-1",
"description": "Dit is een test",
"totalPoints": 2,
"duration": 1,
"level": 1,
"subjectId": 1,
"questions": [ ],
"paragraphs": [ ],
"results": [ ],
"sliders": [ ],
"pausedTests": [ ]
}
],
"schools": [ ],
"categoryId": 1,
"category": null
},

Data that comes back if you console.log the reponse of the API from the console.log(response):

The function is called [{"id":1,"name":"Word","tests":[{"id":1,"title":"Test  1","name":"Test 1","description":"This is the description of the first Test","totalPoints":2,"duration":30,"level":1,"subjectId":1,"questions":[],"paragraphs":[],"results":[{"id":22,"score":100.0,"timeElapsed":5,"actorId":13,"actor":null,"testId":1,"resultQuestions":[],"resultSliders":[]}],"sliders":[],"pausedTests":[]},{"id":5,"title":"new test","name":"new test","description":"asdf","totalPoints":0,"duration":9,"level":3,"subjectId":1,"questions":[],"paragraphs":[],"results":[{"id":19,"score":0.0,"timeElapsed":4,"actorId":13,"actor":null,"testId":5,"resultQuestions":[],"resultSliders":[]}],"sliders":[],"pausedTests":[]},{"id":8,"title":"test","name":"test-1","description":"Dit is een test","totalPoints":2,"duration":1,"level":1,"subjectId":1,"questions":[],"paragraphs":[],"results":[],"sliders":[],"pausedTests":[]}],"schools":[],"categoryId":1,"category":null},{"id":2,"name":"PowerPoint","tests":[{"id":2,"title":"Test  2","name":"Test 1","description":"This is the description of the first Test","totalPoints":2,"duration":30,"level":2,"subjectId":2,"questions":[],"paragraphs":[],"results":[],"sliders":[],"pausedTests":[]},{"id":3,"title":"De titel der titelen","name":"Deze test heet programmeren voor gevorderden","description":"Deze test gaat over hoe leraren ict moet leren begrijpen.","totalPoints":25,"duration":30,"level":3,"subjectId":2,"questions":[],"paragraphs":[],"results":[{"id":20,"score":44.0,"timeElapsed":50,"actorId":13,"actor":null,"testId":3,"resultQuestions":[],"resultSliders":[]}],"sliders":[],"pausedTests":[]}],"schools":[],"categoryId":1,"category":null},{"id":3,"name":"Excel","tests":[],"schools":[],"categoryId":1,"category":null},{"id":7,"name":"Test","tests":[],"schools":[],"categoryId":1,"category":null}]

I tried for myself if i could get the score’s back from the results array table.

function showAllSubjectsScores(response) {
    var parsedData = JSON.parse(response);

console.log('The function is called', parsedData[results][0].score)
    
}

This is how the APi call is made for the response of all the data:

// Global var's
var categoryId = 1;
var actorId = 13; // This is my actorId
var websiteUrl = localStorage.getItem('url');

function getSubjectsByActorid() {
    var xHttp = new XMLHttpRequest();
    xHttp.onreadystatechange = function () {
        if (xHttp.readyState == XMLHttpRequest.DONE) {

            var response = xHttp.response;
            if (xHttp.status == 200) {
                console.log('ANTWOORD IS TERUG VAN DE SERVER')

                showAllSubjectsScores(response);

            } else {
                console.log(response);
                console.log(xHttp.status);

            }
        }
    };

    xHttp.onerror = function () {
        console.log(xHttp.statusText);
    };

    xHttp.open("GET", websiteUrl + "/api/Subjects/" + categoryId + "/" + actorId, true);

    xHttp.send();
    console.log('AANVRAAG IS VERZONDEN')
}
function showAllSubjectsScores(response) {
    var parsedData = JSON.parse(response);

    console.log('The function is called', response)
    
}
getSubjectsByActorid();


This is how the api quarry is build:

// GET: api/Subjects
        [HttpGet("/api/Subjects/{categoryId}/{actorId}")]
        public async Task<ActionResult<List<Subject>>> GetSubjectResults(int categoryId, int actorId)
        {
        var subjectResults = _context.Subjects
       .Where(i => i.CategoryId == categoryId)
       .Include(t => t.Tests)
       .ThenInclude(r => r.Results.Where(a => a.ActorId == actorId))
        .AsNoTracking().ToListAsync();

            if (subjectResults == null)
            {
                return StatusCode(204);
            }

            return await subjectResults;
        }

Comments made to add comments to posts do not match the posts

  1. I’m trying to make a blog. I want to comment on shared posts, comments are made and done well. It shares the views of the posts.

The solution I’m looking for is to make each post’s comments unique.

The IDs of the posts and comments should match and they should appear on the homepage without any problems, but I couldn’t do that.



` COMMENT AND POST SCHEMA'S `

` This is how my Post and Comment schemas link `


const commentSchema = new mongoose.Schema({ author: String, comment: String });
const Comment = mongoose.model("Comment", commentSchema);

const postSchema = new mongoose.Schema({
    title: { required: true, type: String },
    content: { type: String },
    comments: [
        commentSchema
    ]
});
const Post = mongoose.model("post", postSchema);





` Commenting codes like this `


` COMMENT APP `

app.post("/posts", (req, res) => {
    const comment = new Comment({
        author: req.user.username,
        comment: req.body.comment
    });
    comment.save();
    User.findOneAndUpdate({username: req.user.username}, {$push: {myComments: comment}}, function(err){
        if(!err){
            Post.findOneAndUpdate({}, {$push: {myComments: comment}}, function(err){
                if(!err){
                    res.redirect("/posts");
                }
            })
        }else{
            console.log(err);
        }
    });
}); ```








` Here are the homepage codes where Posts and Comments appear. Where is the mistake? `



 
` POST AND COMMENT PAGE `

<% for(var i=posts.length; i--; i>-1){ %>
                    <div class="card">
<div class="card-body">
                            <h5>
                                <%=posts[i].title%>
                            </h5>
                            <p>
                                <%=posts[i].content%>
                            </p>
                        </div>
                        <ul class="list-group list-group-flush">
                            


                            <li class="list-group-item">
                                <form action="/posts" method="post">
                            <li class="list-group-item">
                                <div class="container">
                                    <input class="comment" name="comment" type="text" placeholder="  Yorum Yaz">
                                    <button class="button-commentAdd btn btn-success">Yorum Yap</button>
                                </div>
                            </li>
                            </form>
                            </li>
                            <% for(var j=comments.length; j--; j>-1){ %>
                                <li class="list-group-item">
                                    <div class="container pt-2">
                                        <div class="row">
                                            <div class="col-12">
                                                <p>
                                                    <strong>
                                                        <%= comments[j].author %>
                                                    </strong> <label>: </label>
                                                    <label> </label>
                                                    <%= comments[j].comment %>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <% } %>
                        </ul>
                    </div>
                    <% } %>

How to repeatedly call a button function, which increase a number every second? [duplicate]

I would like the “number” div to increase by 0.1/s everytime I click the button (press button once, +0.1/s; press twice, +0.2/s…) However, the code is not been executing.

<span class = "num">0</span>
<button class = "btn">
add one
</button>
let btn = document.querySelector(".btn");
let num = document.querySelector(".num");

function addUp(){
setinterval(()=>{
    num.innerHTML+=0.1;
},1000)
}

btn.addEventListener("onclick", addUp);