HTML templating in JavsScript

There is HTML where each element can have an x-make attribute with the following values:

copy:n – copy the current element n times and place new elements after the current one;

remove:n – remove n elements, starting with the next one. If there are no n elements after the current one (number_of_elements_after_current < n), then all elements that come after the current one are deleted;

removeChildren:n – remove n children of an element, starting from the first;

switch:n – swap the current element with the element n steps ahead of the current one (you should pay attention to examples 2 and 3).

Conditions:

The operations must be performed in the following order: first all copy operations, then remove, then removeChildren, and switch last. First, all operations at the top level are performed, then at the second level, and so on. The x-make attribute must be removed after performing an operation from that attribute.

Example 1:

solution(document.querySelector(‘entry’))

Before:

<entry>
  <div>
    <div x-make="remove:1">Block 1</div>
    <div x-make="copy:3">Block 2</div>
  </div>
</entry>

After:

<entry>
  <div>
    <div>Block 1</div>
    <div>Block 2</div>
    <div>Block 2</div>
    <div>Block 2</div>
  </div>
</entry>

Explanation:

“Block 2” was copied 3 times – now there are four elements of “Block 2”.

Next, the element following “Block 1” was removed.

Example 2:

solution(document.querySelector(‘entry’))

Before:

<entry>
  <div x-make="removeChildren:2">
    <div x-make="copy:100">Block 1</div>
    <div>Block 2</div>
    <div x-make="switch :7">Block 3</div>
    <div>Block 4</div>
    <div>Block 5</div>
  </div>
</entry>

After:

<entry>
  <div>
    <div>Block 4</div>
    <div>Block 3</div>
    <div>Block 5</div>
  </div>
</entry>

Explanation:

The number of blocks “Block 1” did not increase, because it was removed by the parent with removeChildren.

“Block 3” has changed from “Block 4” as the seventh element, counting from “Block 3”, is “Block 4”.

Example 3:

solution(document.querySelector(‘entry’))

Before:

<entry>
  <section>
    <div x-make="switch:2">
      <div x-make="remove:5">Block 1</div>
      <span>Block 2</span>
    </div>
    <div x-make="copy:1">
      <div x-make="remove:5">Block 3</div>
      <div x-make="switch:1">Block 4</div>
    </div>
    Block 5
  </section>
</entry>

After:

<entry>
  <section>
    <div><div>Block 3</div></div>
    <div><div>Block 3</div></div>
    <div><div>Block 1</div></div>
    Block 5
  </section>
</entry>

Explanation:

Due to the precedence of operations, the second element was copied first – section now has four elements. The switch operation caused the first block inside section to be swapped with the third block Remove:5 in “Block 1” removed “Block 2” Remove:5 removed “Block 4” in “Block 3” (in two elements inside section since they were copied)

Example 4:

solution(document.querySelector(‘entry’))

Before:

<entry>
  <div x-make="switch:2">1</div>
  <div x-make="switch:3">2</div>
  <div x-make="switch:5">3</div>
</entry>

After:

<entry>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</entry>

Explanation:

“Block 1” is swapped with “Block 3”. Further in the container, the first element with x-make will be “Block 3” – it will swap places with “Block 1”. The remaining “Block 2” swaps places with itself, that is, remains in place.

Notes

The solution should be a function called solution that takes a DOM element as input – an entry point.

The source code should look like this:

function solution(entryPoint) { // solution }

Why is NPM install with packagename working in Docker but ‘NPM install” not working?

I am building a docker file in a node.js application. If I install packages this way, it works:

RUN npm install express
RUN npm install axios
RUN npm install cloudinary

These packages will install. I have about 12 packages for this application and running their installation one by one like this doesn’t seem okay to me.
But if I run the entire installations at once like this:

RUN npm install

Once it gets to the npm installation part, it would hang on for more than 7 minutes and eventually fails with this error:

executor failed running [/bin/sh -c npm install --only=production]: exit code: 1

What could be causing this?

Here is the dockerfile:

## multi stage system
FROM node:lts-alpine

 # create root application folder
 WORKDIR /app

 # copy configs to /app folder
 COPY package.json ./
 COPY package-lock.json ./
 COPY tsconfig.json ./
 COPY ecosystem.config.js ./
 # copy source code to /app/src folder
 COPY src /app/src
 RUN npm install

 RUN npm run build



 FROM node:lts-alpine

 WORKDIR /app
 COPY package.json ./ 
 COPY package-lock.json ./

 RUN npm install --omit=dev

 RUN npm install pm2 -g

  COPY --from=0 /app/build ./build


  RUN npm uninstall typescript



   USER node

   CMD ["pm2-runtime", "ecosystem.config.js"]

   EXPOSE 5000

I am running this on windows 11

console.log return webElement object instead of value

I have simple code which stopped print value and return this instead. Any clue what’s wrong?

My code:

async function openWiki() {
    let driver = await new Builder().forBrowser("chrome").build();
    await driver.get("https://cs.wikipedia.org/wiki/Special:random");
    let title = await driver.findElement(By.id("firstHeading"));
    console.log(title);
}

openWiki();

end it wrote to terminal:

WebElement {
  driver_: Driver {
    session_: Promise { [Session] },
    executor_: Executor { customCommands_: [Map], log_: [Logger], w3c: true },
    fileDetector_: null,
    onQuit_: [Function: onQuit],
    authenticatorId_: null,
    pinnedScripts_: {}
  },
  id_: Promise { '50117978-c479-43d4-aced-033f6b2799fc' }
}

I expect value written to the console. When only returning title, there is no error. I tried title.getText(), I got Promise { <pending> }

NodeJS script split into multiple files – require vs. import problems

I have 2 files:

|- main.js
|- lib
     |-  myLib.js

I added a Node.js package (camelcase in this case) to the project using NPM:

 "dependencies": {
    "camelcase": "^7.0.1"
  }

In myLib.js I need that the camelCase function coming from this package. The myLib script defines some utility functions used in main.js.

First, I tried to build the 2 files without including the “type”:”module” to package.json:

// main.js
const myCamelCaseFn = require('./lib/myLib');
myCamelCaseFn ("do something");

// myLib.js
import camelCase from 'camelcase';

const myCamelCaseFn = (arg) => { return camelCase(arg); }
exports.myCamelCaseFn = myCamelCaseFn;

I got

cannot use import statement outside a module

I read some pages, then I found out that this form of import only usable when “type”:”module” is included to package.json. So I did it.

Then there were problems with the require() call, so I changed to the following:

// main.js
import {myCamelCaseFn} from './lib/myLib';
myCamelCaseFn ("do something");

Now I got

cannot find module lib/myLib

So I changed to

const myCamelCaseFn = import('./utils/renamer.js');
console.log(myCamelCaseFn);
myCamelCaseFn ("do something");

I got

myCamelCaseFn is not function

and I see the console message this is a Promise { pending }. As I read import function returns with a promise which will be resolved later – but I can wait to be resolved here (not needed using Require() as it works in another way). I changed again:

const myCamelCaseFn = await import('./utils/renamer.js');
myCamelCaseFn ("do something");

Now I got a different error message:

ReferenceError: exports is not defined in ES module scope
exports.myCamelCaseFn = myCamelCaseFn;

Continue reading it says exports and module.exports points to the same object. Later I got the following on Stack Overflow “Try and remove “type”: “module” from package.json.”.

Yup conditional validation when field is equal to

I need a schema like this:

const schema = yup.object().shape({
SKU: yup.string().required(),
name: yup.string().required(),
price: yup.number().required(),
type: yup.string().required(),
size: yup
  .number()
  .moreThan(0)
  .when('type', {
    is: (type) => type === 'DVD',
    then: yup.number().moreThan(0).required(),
  }),
height: yup
  .number()
  .moreThan(0)
  .when('type', {
    is: (type) => type === 'furniture',
    then: yup.number().moreThan(0).required(),
  }),
width: yup
  .number()
  .moreThan(0)
  .when('type', {
    is: (type) => type === 'furniture',
    then: yup.number().moreThan(0).required(),
  }),
length: yup
  .number()
  .moreThan(0)
  .when('type', {
    is: (type) => type === 'furniture',
    then: yup.number().moreThan(0).required(),
  }),
weight: yup
  .number()
  .moreThan(0)
  .when('type', {
    is: (type) => type === 'book',
    then: yup.number().moreThan(0).required(),
  }),
});

but the parts is: (type) => type === 'DVD' etc throw a warning:

Warning: An unhandled error was caught during validation in TypeError: branch is not a function

How to fix this?

JavaScript is not working on my beginner quiz website

I am trying to learn JS by building a project and I am midway through and the JavaScript doesn’t seem to be working as question object and answer objects are not displayed in the html file even though they should be displayed. Here is the link to the YT vid I am basing my work off: https://www.youtube.com/watch?v=PBcqGxrr9g8
Here are the codes for html and Js:


<!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>Quiz</title>
 <link rel="stylesheet" href="quiz.css">
</head>
<body>
  <div class="app">
   <h1>Quiz</h1>
   <div class="quiz">
   <div class="question" id="question">Here is the question</div>
   <div id="answer-buttons">
  <button class="answer-btn" id="answer-btn">First answer-btn</button>
  <button class="answer-btn" id="answer-btn">Second answer-btn</button>
  <button class="answer-btn" id="answer-btn">Third answer-btn</button>
  <button class="answer-btn" id="answer-btn">Fourth answer-btn</button>
  <button class="nextbtn" id="nextbtn">Next</button>
</div>
</div>
</div> 
  
</body>
<script src="quiz.js"></script>
</html>
const questions={
    question:'Which teams has the most titles in the English Premier Leauge?',
    answers:[
        { text:"Liverpool", correct:false},
        {text: "Manchester United", correct:true},
        {text:"Chelsea",correct:false},
        { text:"Manchester City", correct:false},
    ],
    question:"Who is the top scorer in the history of the English Premier League?",
answers: [
{ text:"Alan Shearer", correct:true},
{text: "Wayne Rooney", correct:false},
{text:"Thierry Henry",correct:false},
{ text:"Andrew Cole", correct:false},
],
question: "Which team has won the most consecutive English Premier League titles?",
answers: [
{ text:"Arsenal", correct:false},
{text: "Manchester United", correct:true},
{text:"Chelsea",correct:false},
{ text:"Manchester City", correct:false},
],
question: "Who has won the most English Premier League Manager of the Season awards?",
answers: [
{ text:"Sir Alex Ferguson", correct:true},
{text: "Pep Guardiola", correct:false},
{text:"Arsène Wenger",correct:false},
{ text:"José Mourinho", correct:false},
],
question: "Which English Premier League team has won the most FA Cup trophies?",
answers: [
{ text:"Liverpool", correct:false},
{text: "Arsenal", correct:true},
{text:"Chelsea",correct:false},
{ text:"Manchester United", correct:false},
],
question: "Who holds the record for the fastest hat-trick in the English Premier League?",
answers: [
{ text:"Sadio Mane", correct:false},
{text: "Robbie Fowler", correct:true},
{text:"Alan Shearer",correct:false},
{ text:"Michael Owen", correct:false},
]
}
const questionElement=document.getElementById('question');
const answerButton=document.getElementById('answer-buttons');
const nextButton=document.getElementById('nextbtn');

let currentQuestionIndex=0;
let score=0;
 
function startQuiz(){
    currentQuestionIndex=0;
    score=0;
    nextButton.innerHTML='Next';
    showQuestion();
}
function showQuestion(){
    let currentQuestion=questions[currentQuestionIndex];
    let questionnumber=currentQuestionIndex+1;
    questionElement.innerHTML=questionnumber +'.'+currentQuestion.question;
      
     currentQuestion.answers.forEach(answer =>{
        const button=document.createElement('button');
        button.innerHTML=answer.text;
        button.classList.add('btn');
        answerButton.appendChild(button);
     });

}
startQuiz();

The orginal div should be replaced by the objects in the Js file but doesnot seem to be working

How to combine objects that have arrays?

How can I combine two objects recursively following these rules:

  • nested objects are combined in exactly the same way
  • arrays common to the two objects should be represented in the output as the entire second object’s array concatenated onto the end of the entire first object’s array
  • if the second object has a key that the first object also has (and it is not an array or an object value), then just overwrite the first object’s with the second object’s
let obj1 = {
  'foo': [
    'one',
    'two',
    'three'
  ],
  'bar': 'hello'
};

let obj2 = {
  'foo': ['five'],
  'world': 'earth'
};

Object.assign(obj1, obj2) returns { foo: [ 'five' ], bar: 'hello', world: 'earth' }, it has overwritten the entire foo array instead of just added obj2‘s items to it.

I want

combine(obj1, obj2) ->
{
  'foo': [
    'one',
    'two',
    'three',
    'five'
  ],
  'bar': 'hello',
  'world': 'earth'
}

Is there a way to update custom markers without re-rendering the whole map?

I followed this tutorial to make my own custom markers on the map.

The problem here is I can’t feed the markers with the new data fetched from some API (fetched periodically) and I can’t filter the markers without re-rendering the whole map!

I want to do the exact same thing as in this example using my custom markers but I couldn’t figure out how to do it.

Any help?

Source files after building the react app are not minified. both js and css files

I have run “npm run build” within my react app. after that i was serving the files using “serve -s build”. And in my environment files i had disabled source-maps by adding “GENERATE_SOURCEMAP=false” to my .env file. but when i open the source tab in my chrome dev tools, both the js and css files are not minified. they were shown with indentation as below:

source files without indentation

i wanted to show minified files only. Any help would be appreciated.

Calling multiple javascipt files in single html page

my index.html contains

<button class="btn btn-success btn-lg" type="button" id="enteri" onclick="mycall()">Enter</button>` 

<script src="animemovies.js"></script>
<script src="animeseries.js"></script>
<script src="index.js"></script>`

in index.js

function mycall() {if(){animeseries();}else{animemovies();}}`

in animemovies.js

function animemovies() {}

in animeseries.js

function animeseries() {}

the problem is animeseries() function is not getting called, but if I change the order in index.html like

<script src="animeseries.js"></script>
<script src="animemovies.js"></script>
<script src="index.js"></script>

Now animeseries() is getting called but animemovies() function is not getting called.

Does anyone know how to resolve this?

How to detect user if they visited the webpage by press back button

Let say, visitor visited my website example.com and then visited other website (maybe by clicking any link of my webpage or maybe manually typing to address bar) in same tab and then he pressed browser back button and came back to my website example.com

How can i detect that the user visited my site again with back button?.

I am trying

With Popstate :

window.addEventListener('popstate', function(event) {
  if (event.state && event.state.source === 'example.com') {
    console.log('User returned to example.com by clicking the back button');
  }
});

With onpopstate

window.onpopstate = function(event) {
  if (event && event.state) {
    console.log('User returned to example.com by clicking the back button');
  }
};

With pageshow

window.addEventListener('pageshow', function(event) {
  if (event.persisted) {
    console.log('User returned to example.com by clicking the back button');
  }
});

Sadly, none of these worked!!

Fetch returns empty array

So I am sending POST request to my API but it’s returning just an empty array. It should return array of objecst.

const getRules = function () {
  console.log(selectedRule.value);
  fetch("http://127.0.0.1:5112/v1/showFiles", {
    method: "POST",
    body: JSON.stringify({ rule_dir: selectedRule.value }),
  })
    .then((response) => response.json())
    .then((response) => console.log(JSON.stringify(response)));
};

Any idea how to resolve it ?

Image Map not working as intended: Highlighted area get’s darken effect, but shouldn’t

I’ve been building a custom image map for our different light environments, where we display the different areas our light solutions can be used.

Under “Zielsetzungen” you can see the image map I’m talking about.

It is expected, that the user can hover over any of the 4 areas on the main image, and that the respective area get’s highlighted in orange, while the rest of the image is darkened.

Here is the image setup I’ve used:

  1. main base image in white to greyscale that you see when not hovered
    2-5) for one area each, there is a png cutout with the building colored in our CI’s orange.

I’ve fixed the first stages of code already so that now the respective areas are highlighted, but are still darkened by the functions. I thought that using png’s with transparent bg, would only darken the main image underneath, but currently even the highlighted png’s are darkened aswell. Which I’m trying to solve but don’t know how.

I can only think about some issue with the Z-Index of the cutout png’s, but maybe someone could check my code to see if there is some minor error I’ve overlooked or it lies within the general approach of my images?

`<style>
  .main-image {
    transition: 0.3s;
    position: relative;
    background-image: url('https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/64393083e51864f3cc4dfce0_industriebereiche_anwendung_startbild_transparent-bg-40pct-scale.png');
    background-size: cover;
  }
  .darkened {
    filter: brightness(50%);
  }
  #tooltip {
    z-index: 100;
  }
</style>

<div id="tooltip" style="display: none; position: absolute; pointer-events: none; background-color: rgba(0, 0, 0, 0.8); color: white; padding: 10px; border-radius: 5px; font-size: 14px;">
  <p id="tooltip-text"></p>
</div>

<img src="https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/64393083e51864f3cc4dfce0_industriebereiche_anwendung_startbild_transparent-bg-40pct-scale.png" usemap="#image-map" class="main-image" id="main-image">

<map name="image-map">
  <area target="_self" alt="Lager- und Logistikbereiche" title="Lager- und Logistikbereiche" href="#" coords="854,529,1206,358,1203,288,1061,215,709,385,705,454" shape="poly" onmouseover="setImageSource('https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/6439a8c31ba631d09bbf87ff_industriebereiche_anwendung_lager-highlight-40pct-final.png'); darkenImage(); showTooltip('Lager- und Logistikbereiche');" onmouseout="resetImageSource(); undarkenImage(); hideTooltip();" onmousemove="updateTooltipPosition(event);">
  <area target="_self" alt="Produktionsbereiche" title="Produktionsbereiche" href="#" coords="883,284,979,238,982,157,744,35,624,97,619,178,846,301" shape="poly" onmouseover="setImageSource('https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/6439a8c3e244ea05c146db2e_industriebereiche_anwendung_produktion-highlight-40pct-final.png'); darkenImage(); showTooltip('Produktionsbereiche');" onmouseout="resetImageSource(); undarkenImage(); hideTooltip();" onmousemove="updateTooltipPosition(event);">
  <area target="_self" alt="Nebenbereiche" title="Nebenbereiche" href="#" coords="227,379,423,255,686,406,686,460,901,575,746,647" shape="poly" onmouseover="setImageSource('https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/6439a8c300f7746d13ef3eaa_industriebereiche_anwendung_nebenbereiche-highlight-40pct-final.png'); darkenImage(); showTooltip('Nebenbereiche');" onmouseout="resetImageSource(); undarkenImage(); hideTooltip();" onmousemove="updateTooltipPosition(event);">
  <area target="_self" alt="Spezielle Leuchten" title="Spezielle Leuchten" href="#" coords="209,370,39,283,538,29,610,95" shape="poly" onmouseover="setImageSource('https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/6439a8c308c482bbb4be2660_industriebereiche_anwendung_spezielle-leuchten-highlight-40pct-final.png'); darkenImage(); showTooltip('Spezielle Leuchten');" onmouseout="resetImageSource(); undarkenImage(); hideTooltip();" onmousemove="updateTooltipPosition(event);">
</map>

<script>
  var mainImage = document.getElementById('main-image');

  function setImageSource(src) {
    mainImage.src = src;
  }

  function resetImageSource() {
    mainImage.src = 'https://uploads-ssl.webflow.com/634723edf4a76fbc19fabbf3/64393083e51864f3cc4dfce0_industriebereiche_anwendung_startbild_transparent-bg-40pct-scale.png';
  }

  function darkenImage() {
    mainImage.classList.add('darkened');
  }

  function undarkenImage() {
    mainImage.classList.remove('darkened');
  }

  function showTooltip(text) {
    document.getElementById('tooltip-text').innerText = text;
    document.getElementById('tooltip').style.display = 'block';
  }

  function hideTooltip() {
    document.getElementById('tooltip').style.display = 'none';
  }

  function updateTooltipPosition(event) {
    var tooltip = document.getElementById('tooltip');
    tooltip.style.left = event.pageX + 10 + 'px';
    tooltip.style.top = event.pageY + 10 + 'px';
  }
</script>`

FirebaseError: Failed to load environment variables from .env

I am using Firebase to run the backend for my application. When I try to run the backend using
firebase emulators:start --inspect-functions it says

Node v: 18.13.0

i  emulators: Starting emulators: auth, functions, storage
⚠  functions: You are running the Functions emulator in debug mode (port=9229). This means that functions will execute in sequence rather than in parallel.
⚠  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: firestore, database, hosting, pubsub
⚠  functions: Unable to fetch project Admin SDK configuration, Admin SDK behavior in Cloud Functions emulator may be incorrect.
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "/home/ktk/code/js/sol/functions/functions" for Cloud Functions...
⚠  functions: package.json indicates an outdated version of firebase-functions. Please upgrade using npm install --save firebase-functions@latest in your functions directory.
✔  functions: Using node@18 from host.
⬢  functions: Failed to load function definition from source: FirebaseError: Failed to load environment variables from .env.

Things I’ve checked:

  • the .env does exist
  • the .env syntax is correct