CSS Grid on 100vh screen disturbing the layout on mobile devices

I am working on designing Web Application which wants only 100% of screen means not to scroll, that’s why am using 100vh . In which having some input fields, its working fine on the desktop but when i am clicking on input field on Mobiles and Tablets there keyboard is opening by which layout is getting effected. Anyone can help me that how can i handle this situation using CSS or JS, So that the layout is also correct and can be typed on the keyboard as well.. Thanks in advance.

For refrence i am attaching demo video and link click here to know what is happening.

The way I tried is that when the input field is active then the screen size which is being compressing will add 300px height for particular devices.

const documentHeight = () => {
         const doc = document.documentElement;
         const platforms = ["Android", "Linux", "arm"];
         const isAndroid = new RegExp(platforms.join("|")).test(
            window.navigator.userAgent
         );

         if (!isAndroid)
            document.addEventListener("touchmove", function (event) {
               event.preventDefault();
            });

         if (window.innerHeight < 667 && isAndroid) height = 250;
         else height = 0;

         doc.style.setProperty(
            "--doc-height",
            `${window.innerHeight + height}px`
         );
      };

      window.addEventListener("resize", documentHeight);
      let htmlTag = document.getElementsByTagName("html");
      let root = document.getElementById("root");
    {
         if (width <= 768) {
            documentHeight();
            htmlTag[0].style.position = "fixed";
            htmlTag[0].style.overflow = "hidden";
            htmlTag[0].style.width = "100vw";
         }
      } else {
         const doc = document.documentElement;
         doc.style.removeProperty("--doc-height");
      }
   });

Counting cards in freecodecamp using only if else and array

Please refer the Problem statement and test cases here :
Counting Card problem

I created an array and an if else statement for when the count should increase or decrease based on the card we get from the function cc

Problem :
When cc(7) it still decrease the count.

I think it should not decrease since i mentioned it in else if block

Code i tried :

let count = 0;

function cc(card) {
  // Only change code below this line
let plusOne = [2,3,4,5,6];
let zero = [7,8,9];
//let negOne = [10,J,Q,K,A]; 

if (card in plusOne){
  count+=1;
}
else if(card != zero){  //issue
  count-=1;
}

console.log(typeof(card)) //for my ref
console.log(count); //for me
if (count >= 1){
  return count +' Bet';
}
else{
  return count +' Hold';
}
  // Only change code above this line
}

cc(2); cc(3); cc(7); cc('K'); cc('A');

Output i got :

number
1
number
2
number
1
string
0
string
-1

As per the problem i think output should be :

number
1
number
2
number
2
string
1
string
0

How do i start coding? [closed]

Where can I write up the code?
How to learn code ( with detailed steps )
i’m very interested in code but I do not know where and how to start.
I tried online programs and got the info, but since I have nowhere to apply it, I forgot about the information I learnt.

How to allow “Blocked a frame with origin “https://example.com” from accessing a cross-origin frame.” node.js

I am making a little script that has to open a api window like:

var api = window.open("https://example.com", "Poppout", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=400,top="+(screen.height-400)+",left="+(screen.width-840)); 

when ever i try to access it like:
api.document.getElementById('ex').value;
I get the error:

Uncaught DOMException: Blocked a frame with origin "https://example.com" from accessing a cross-origin frame.
    at <anonymous>:1:5

I know why this is happening but since i’m the owner of the api’s url can i enable someway to do this?

my index.js code:

const express = require('express');
const app = express();
const http = require('http');
const router = express.Router();
const path = require('path')
const server = http.createServer(app);
const { Server } = require("socket.io");
const i = new Server(server);

app.use(express.json());
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "*");
  next();
 });
router.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'))
});
app.use('/', router);

app.post('/', (req, res) => {
  const { chat, username } = req.body;
  console.log(username, 'รท', chat)
  i.emit('chat', chat, username);
});

server.listen(3000, () => {
  console.log('listening on port: 3000');
});

anything in the right direction helps!

Data from twilio

client.messages
    .list({
        from: '123456786',
        limit: 1
        })
    .then(messages => messages.forEach(m => console.log(odp = m.body))); 


I tried:

function resolveAfter2Seconds() {
    return new Promise(resolve => {client.messages
        .list({
            from: '123456789',
            limit: 1
            })
        .then(messages => messages.forEach(m => m.body)); 
    });
  }
  
  async function asyncCall() {
    const result = await resolveAfter2Seconds();
    console.log(result)
  }
  asyncCall();

I use with Twilio.
I have such a code. Thanks to this, the last message from the given number is displayed in the console.
I’d like to assign the result to a variable so I can use “if” to perform an action later.

Unfortunately, it is not caught. I am a novice on this subject. Please help.

First button in a div not listening to events in JQuery

I have a div that has 4 buttons inside. Each button must do something unique when clicked. The problem I am facing is that the first button’s event is not working. I have tried to switch the positions of the buttons. If I do so the one that was working stops working and the one not working starts working. So the problem is not the button itself but its position. The project has also PHP and some Below I have attached my JS and HTML Code. What could be the problem?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div>

<button id="one"> Button 1 </button>
<button id="two"> Button 2 </button>
<button id="three"> Button 3 </button>
<button id="four"> Button 4  </button>

<script>

$(document).ready(()=>{

$("#one").click(()=>{
alert("one");
})
$("#two").click(()=>{
alert("two");
})
$("#three").click(()=>{
alert("three");
})
$("#four").click(()=>{
alert("four");
})

})
</script>

</div> 

Is there anyway to store prompted inputs into a .json file and reuse the stored inputs from the json file in the next session/process?

I’m creating an account generator using puppeteer and there’s certain user inputs that are needed and I have it prompt the user to input the necessary variables and I was wondering, is it possible to store these inputs into a json file and then pull the stored inputs from the json file and reuse it for the next session rather than having to input the required variables over and over again after every new process. The code below is the package I have required and the following variables that are prompted.

const prompt = require("prompt-sync") ({sigint: true });
const fs = require("fs").promises;
const request = require('request');
const fetch = require('node-fetch')
const { ImapFlow } = require('imapflow');
const random_useragent = require('random-useragent');
const { scrollPageToBottom } = require('puppeteer-autoscroll-down')
const { scrollPageToTop } = require('puppeteer-autoscroll-down')
const { Webhook, MessageBuilder } = require('discord-webhook-node');

const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());

( async () => {

    const browser = await puppeteer.launch({ 
        headless: false, // false = Shows Browser | true = Browser Not Shown
        executablePath: `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,
        userDataDir: `/Users/senpai/Library/Application Support/Google/Chrome/Default`,
        ignoreHTTPSErrors: true,
        ignoreDefaultArgs: ['--enable-automation'],
        args: [
                `--disable-blink-features=AutomationControlled`,
                `--enable-blink-feautres=IdleDetection`,
                `--window-size=1920,1080`,
                `--disable-features=IsolateOrigins,site-per-process`, 
                `--blink-settings=imagesEnabled=true`
        ]
    });

    // User Inputs
        let webhook = prompt ("Input Discord Webhook: ");
        let catchall = prompt ("Input Your Catchall - Exp: catchall.com: ");```

How to stop printing duplicates in javascript [duplicate]

I have an array of objects which contain the keys author and quote. I take the values and print them on the website. I’m trying to prevent this from printing duplicates but I can’t seem to wrap my head around it. Thanks for your help in advance.

this is the event listener for the button that generates the random quote

btn.addEventListener('click', () => {
    const randomQuote = quoteObject[Math.floor(Math.random()*quoteObject.length)];
    console.log(randomQuote);
    quote.textContent = randomQuote.quote;
    author.textContent = `-${randomQuote.author}`;
});

Backwards typing effect

I am trying to get a backwards typing effect with my code. So the <P> will say “Coming Soon” then type backwards. Then type forwards into “SeaDogs.com.eu.as”

This is what I have so far, for some reason it type coming soon backwards twice??? Which is my first hurtle I’m trying to overcome. And trying to delay it so it shows the word “Coming soon” for a few seconds.

var str = 'Coming Soon';
var remove = false;
var i = str.length;
var isTag;
var text;

(function type() {
  if (!remove) {
    text = str.slice(0, --i);
    if (text === str) return;
  }

  if (!isTag) {
    document.getElementById("demo").innerHTML = text;
  }



  setTimeout(type, 520);

}());
<p id="demo"></p>

LeetCode 138. Copy List with Random Pointer. Why JavaScript object literal cannot work

https://leetcode.com/problems/copy-list-with-random-pointer/

var copyRandomList = function (head) {
  const counter = {};
  let pointer = head;
  while (pointer) {
    const newNode = new Node(pointer.val);
    counter[pointer] = newNode;
    pointer = pointer.next;
  }
  pointer = head;
  while (pointer) {
    let node = counter[pointer];
    let nextNode = pointer.next;
    let ranNode = pointer.random;
    node.next = counter[nextNode] || null;
    node.random = counter[ranNode] || null;
    pointer = pointer.next;
  }
  return counter[head];
};

Same intuition can be resolved by Map. But object in JavaScript always only return the last node. Can someone help figuring out how to solve this problem with object literal?

Tried solve it with Map.

how to return value in function get firebase

I want to create a function to get value and return data from real-time databases
but when i do. Javascript just return Promise not value am expected

I have tried to create a function like this

function getSensorSoil() {
  return get(ref(db, 'sensor/')).then((snapshot) => {
     return snapshot.val();
  });
}

but it just returns value like this
https://prnt.sc/qpa5bjhdJlsL

what I hope is that the function will immediately return the value from the soil sensor
so i just need to call the function like this getSensorSoil()['sensorr']

JavaScript – add new record to all upper nodes in heirarchy

How can I add new object to all the upper parent nodes in heirarchy?

I have this parent-child hierarchy:

const categories = [
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 3 
    },
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 2 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 3 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 2 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 1 
    }
]

Now as you know that parent has all the segments that their childern contains. (Unique segments)

So the most top parent should be the richest.

Now here I am trying to add new segments to the parent category 2.

{
    "parentCatId": 2,
    "segments": [
        {
            "id": 4
        },
        {
            "id": 1
        }
    ] 
}

Now I want this record to be added in the categories array and update all the parents accordingly.

Expected response should be:

[
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 4 
    },
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 3 
    },
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 2 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 4 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 3 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 2 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 1 
    }
]

As you see the new segmentId 4 got updated for both catId 2 & 1. (segmentId 1 got skipped because it was already there of catId 1

Now originally this hierarchy can be upto nth level.

I have created a snippet playground for this aswell:

const categories = [
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 3 
    },
    {
        "catId": 2,
        "parentCatId": 1,
        "path": "Cat > SubCat",
        "segmentId": 2 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 3 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 2 
    },
    {
        "catId": 1,
        "parentCatId": 0,
        "path": "Cat",
        "segmentId": 1 
    }
];

function addNewSegments(inputSegments){
  
  categories.forEach((segment) => {
    console.log(segment)
  });
}

addNewSegments({"parentCatId": 2, "segments": [{"id": 4}, {"id": 1}]})

creating an employee database but unable to remove

So guys i am creating an employee database where on clicking on their name u will see there details and the data is been recieved from a json file i also added a delete button to delete any employee but delete button is deleting only once its not working afterwards

let employ = document.getElementById("emp");
let details = document.getElementById("employDetails");
let id = 1;

(async function () {
  const data = await fetch("./data.json");
  const res = await data.json();

  try {
    res.map((newData) => {
      createNewEmploye(newData);
    });
  } catch (error) {
    console.log(error);
  }
  addingEventListener(res);
})();
 


function createNewEmploye(newData) {
  // destructuring data
  const { name } = newData;

  const creatingEmployee = document.createElement("div");
  creatingEmployee.classList.add("employsName");
  employ.appendChild(creatingEmployee);

  const html = `<div class="serialNo">${id}</div>
    <div class="employ">${name}</div>
    <div class="del">del</div></div>`;
  creatingEmployee.insertAdjacentHTML("afterbegin", html);
  id++;
}

function addingEventListener(res) {
  const selectedEmploy = document.querySelectorAll(".employ");
  const deleteButton = document.querySelectorAll(".del");

> deleting button logic
deleteButton.forEach((del) => {
    del.addEventListener("click", (e) => {
      employ.innerHTML = " ";
      id = 1;
      const currentTarget = e.target.previousElementSibling.innerHTML;

      // deleting the element
      res = res.filter((e) => {
        if (currentTarget !== e.name) {
          createNewEmploye(e);
        }
      });
    });
  });

  selectedEmploy.forEach((emp) => {
    emp.addEventListener("click", (e) => {
      details.innerHTML = " ";

      selectedEmploydetails(e, res);
    });
  });
}

function selectedEmploydetails(e, res) {
  let emloyName = e.target.innerHTML;
  res.filter((elm) => {
    if (elm.name === emloyName) {
   const { name, dob, gender, eId, image, email, mob, add, salary } = elm;

      const age = AgeFinder(dob);
      const empDetCont = document.createElement("div");

      const html = `<div class ='eImage eInfo'><img src="${image}" alt=""></div>
  <div class="eId eInfo">Employee Id - ${eId}</div>
  <div class="eName eInfo">Name - ${name}</div>
  <div class="eGender eInfo">Gender -  ${gender}</div>
  <div class="eName eInfo">Email - ${email}</div>
  <div class="eName eInfo">Contact No - ${mob}</div>
  <div class="salary eInfo">Salary - ${salary}</div>
  <div class="eAddr eInfo">Address - ${add}</div>`;

      details.appendChild(empDetCont);
      empDetCont.insertAdjacentHTML("afterbegin", html);
    }
  });
}

Everything else is else is working fine but delete button function working only once after that it does not work and there are no error in console either

………………………………………………………………..
`

How to call a worker in javascript mutiple time?

I create a function using define and worker in javascript . And I call that fuction multiple time for drawing the graph structure but that function only go to ready stage by taking last value that i send in loop and draw structure based on that and only one graph is draw but all other remain empty. how i resolve this

define('renderer',["stage", "worker!layout-worker.js"], function(stage, worker) {

  var initialized = false, pending, errorCallback, renderCallback;
   worker.onmessage = function (event) {
  
    switch (event.data.type) {

    case "ready":
            initialized = true;
             console.log("ready=================> ",event.data.type);
            if (pending) {
               worker.postMessage(pending);
            }
            break;
          case "stage":
          
            stage.draw(event.data.body);
            renderCallback && renderCallback();
            break;
          case "error":
            if (errorCallback) {
              errorCallback(event.data.body);
            }
    }
  };

  return {
    init: function(element) {
    
      return stage.init(element);
    },
    render: function(source) {
      if (initialized) {
        worker.postMessage(source);
      } else {
       
        pending = source;
  worker.postMessage(source);
       
      }
    },
    stage: stage,
    errorHandler: function(handler) {
      errorCallback = handler;
    },
    renderHandler: function(handler) {
      renderCallback = handler;
    }
  };

});

in this init function is run each time also render function is run each time but worker is going to ready state
it is going in ready stage in last loop value only and not drawing other structure

How to import from a webpack bundle using my own node backend?

Given the ‘webpack’ bundle ‘/external_modules/seeso/dist/seeso.js’ from the ‘seeso’ package and a node backend I wrote that sends files according to their path:


import { fileURLToPath } from 'url';
import express from 'express'
const app = express();
const PORT = 20000;

app.use('/public', express.static('public'))
app.use('/node_modules', express.static('node_modules'))
app.use('/my_modules', express.static('my_modules'))
app.use('/external_modules', express.static('external_modules'))

app.get('/', (req, res) => {
    res.redirect('/public/index.html');
    //res.sendFile(new URL('./index.html', import.meta.url).pathname)
});

app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));

How should I change my code to allow imports like

import Seeso, {InitializationErrorType, CalibrationAccuracyCriteria} from '/external_modules/seeso/dist/seeso.js';

that are currently met with

Uncaught SyntaxError: The requested module '/external_modules/seeso/dist/seeso.js' does not provide an export named 'CalibrationAccuracyCriteria' (at easy-seeso.js:2:34) 

to work?

I’ve been stuck on this problem for a week and its pretty urgent, so I would really appreciate your help:)