understanding parameters in callbacks and recursion

I am currently reading Eloquent JavaScript by Marijn Haverbeke and there is a piece of code that I want someone to explain for me. Consider the following commented code:

class Network {
   constructor() {
 // irrelevent code except the following line
 this.types = Object.create(null)
}

   defineRequestType(name, handler) {
        this.types[name] = handler
      }
}

// when we call the defineRequestType method in another module.


defineRequestType("note", (nest, content, source, done) => {
    // this is the callback I am referring to. (See below)
    console.log(`${nest.name} received note: ${content}`);  
    done(); 
  });

// last but not least, the send method

send(to, type, message, callback) {
        let toNode = this[$network].nodes[to]
        let handler = this[$network].types[type] // this is important. we're referring to the function's callback that we just called, and this callback is our handler
        if (!handler) // not important
          return callback(new Error("Unknown request type " + type))
        if (Math.random() > 0.03) setTimeout(() => {
          try {
                 /*
                    When we call the send method, the part that I don't understand is that we passed 'done()' as a callback to the handler. 
                    However, as you can see in the previous function call, done() does not take any arguments. 
                    Yet, the handler expects the callback of the handler to have 2 arguments 'error' and 'response'. How is this possible?
                 */
            handler(toNode, ser(message), this.name, (error, response) => {
              setTimeout(() => callback(error, ser(response)), 10)
            })
          } catch(e) {
            callback(e)
          }
        }, 10 + Math.floor(Math.random() * 10))
      }


In case you are interested in reading the source code, please take a look at the this link were you will find the above functions and more (quite sophisticated) functions. Please click on crow tech and Chapter 11 to see the full code. (In case requested).

Eloquent JavaScript

Why do these numbers get concatenated instead of getting added? [closed]

This simple code block is meant to take loanAmount and add 30% of itself to itself and output to the DOM (.totalOutput), the problem is that it is concatenating the two number instead of adding them together eg: instead of 1000 + 30% = 1300, the output is 1000300:

let calculate = (term) => {
let loanInput = document.getElementById("amount").value;

let dailyOutput = document.getElementsByClassName("dailyOutput")[0];
let monthlyOutput = document.getElementsByClassName("monthlyOutput")[0];
let totalOutput = document.getElementsByClassName("totalOutput")[0];

switch (term) {

    case 1: 
            
        dailyOutput.innerHTML = "R" + loanInput / term / 30;
        monthlyOutput.innerHTML = "R" + loanInput / term / 12;

        let totalAmount = loanInput + (loanInput * 0.3); //These are the problem lines
        totalOutput.innerHTML = totalAmount;             //
        break;
    case 3:
        dailyOutput.innerHTML = "3";
        break;

    case 6:
        dailyOutput.innerHTML = "6";
        break;  

    case 9:
        dailyOutput.innerHTML = "6";
        break;

    case 12:
        dailyOutput.innerHTML = "12";
        break;  

    default:
      'not found';
        break;
}


}

Im expecting the equation to render the amount + 30% interest to the DOM.

Syncing multiple musical tracks in vanilla JS while only playing one at a time?

My problem is the following: let’s say I have three audio files with exactly the same duration titled level1.mp3, level2.mp3, level3.mp3. These files have the same music with increasing instrumentation and the idea is to swap from one to the next by user input. We don’t know at what point in time this happens, so I need a way to keep them ‘synced up’ so the transition isn’t jarring (out of time).

My idea is to load them all into individual objects and keep them playing muted, while the current audio is unmuted, but this seems computationally wasteful. Is there a good way to calculate the playtime of the current file so that we can start the next file at exactly that time without much of a noticeable latency? I hear the Web Audio API works for this kind of thing, but I’ve little experience with it.

The main requirement is that the transitions are relatively seamless and secondarily lower on resource-intensity. The files will be in the range of 200kB-500kB.

Thank you for your help.

I’m trying to create an image slider with modals and I’m having trouble with displaying my images

Im making a webpage using html, css and javascript. Im still new to all three. I have a sort of carousel image slider where when you click on an image, it expands to reveal more information. However, when the images in the slider and the additional content of the modals cannot appear at the same time. When the slider images are appearing, the modals disappear and only a blank overlay is shown and when the modals appear, the slider images disappear. As you can see in the screenshots, with the images commented, the models are working fine. Any suggestions would be appreciated. [enter image description here](https://i.stack.imgur.com/yCHDH.png)

How do I make JS fetch function receive json/data from flask API in the same order as sent by flask?

How do I make JS fetch receive json/data from flask API in the same order as sent by flask?

flask API:

@api_bp.route("/users")
def users():
    all_users = User.query.all()
    data = list([u.to_dict() for u in all_users])
    return data

print(data):

[{'id': 1, 'username': 'godo', 'email': '[email protected]', 'first_name': 'Godo', 'last_name': 'xxx'}]

JS script:

fetch( apiEndpoint + 'users' )
.then(response => response.json())
.then(data => {
  this.tableData = data;
})
.catch(error => {
  console.error('Error fetching data:', error);
});

data:

[{'email': '[email protected]', 'first_name': 'Godo', 'id': 1, 'last_name': 'xxx', 'username': 'godo'}]

The order of keys of the JSON when received by JS fetch is altered to a seemingly alphabetical or random order. I have read that there are technical explanations as to why this is the case, but I really need to receive the data in the same order. Reason: I will display this data using Bootstrap-vue in the browser, and the order is important.

Carousel or slider with content sliding effect and images rotating

I want to create a slider like this. I love this one for sure.
global.fliteboard.com

In 2nd section of this website homepage, there is a product slider with images rotating and content sliding effect.

I really love it, can anyone help me with this slider?
I tried

Splidejs Library 

to test it, but I am not that expert :-).

Please help me with this.

I have tried to create it using Splidejs JavaScript library. But I cant make it same. Please help

JavaScript – encodeURI results in illegal JSON

I’m working on a program that invokes a PowerShell script using a custom protocol. So far, I reached the situation that the mechanisms are working as needed except for one small thing. I found a temporary solution but its ugliness is far beyond my tolerance.

The JavaScript piece of code I’m using follows:

:
:
var l_Request_JSON_Str = '{"Request":"Do_1","Par_1":"blabla"}' ;
var l_Test_URL = 'MyProt:MyApp?Command=' + l_Request_JSON_Str ;

l_Test_URL = encodeURI(l_Test_URL) ;

var l_Tempo_Element       = document.createElement("a") ;
l_Tempo_Element.setAttribute    ("id"   , "Invoke_Custom_Prototol"           ) ;
l_Tempo_Element.setAttribute    ("href" , l_Test_URL                         ) ;
l_Tempo_Element.addEventListener("click", function (e) { e.stopPropagation()}) ;

l_Tempo_Element.click() ;

l_Tempo_Element.remove() ;

:
:

The value returned by encodeURI is:

fdmyalbs:MyApp?Command=%7B%22Request%22:%22Get_Albums_List%22,%22Folder%22:%22blablaFolder%22%7D

which, as can be seen, includes the comma between the two elements of the JSON.

When this string is delivered to the PowerShell script, the same comma character is replaced by a linefeed/carriage-return/speace character (did not check it, but the PowerShell console shows the second element of the JSON in a separate line).

For the time being, I change the code such that the string to be sent to the script is:

fdmyalbs:MyApp?Command=%7B%22Request%22:%22Get_Albums_List%22@@@%22Folder%22:%22blablaFolder%22%7D

At the PowerShall script, I replace @@@ with a comma character and everything works as required.

Could anyone suggest why the comma is being replaced in the transaction from the JavaScript and the PS script?

Menu Background Color Change for Active Page [duplicate]

I am having an issue with a sub menu I’ve built for a website. I want the background and text colors for the active page to change when you’re on a page that is linked in the menu (BG: #f0ebe4 and TEXT: #bb9d76 — the same colors as when you hover over each item).

Right now, it reverts back to the normal colors, and doesn’t indicate the active page that the user is on. What am I missing in this code?

<html>
<head>
    <style>
        .container {
            display: flex;
            background-color: #bb9d76;
            width: 100%;
        }

        .column {
            flex: 1;
            padding: 20px;
            text-align: center;
            background-color: #bb9d76;
            color: #f0ebe4;
            transition: background-color 0.3s, color 0.3s;
            font-family: "Crimson Pro", sans-serif;
            font-size: 18px;
        }

        .column:hover {
            background-color: #f0ebe4;
            color: #bb9d76;
        }

        .column a {
            text-decoration: none;
            color: inherit;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="column">
        <a href="https://williamshandcrafted.com/custom-kitchen-cabinets/">KITCHENS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/build-in-cabinets/">BUILT-INS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/custom-closet-storage-cabinets/">CLOSETS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/home-commercial-office-cabinets-furniture/">OFFICES</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/home-bar-entertainment-cabinets/">BARS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/products-libraries/">LIBRARIES</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/bathroom-vanity-cabinets/">VANITIES</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/products-furniture/">FURNITURE</a>
    </div>
</div>

</body>
</html>

How can I make a function to show/hide div elements , while targeting multiple elements

I am beginner and I was copying LinkedIn’s layout design as a practice project. I need a function to show or hide menus when clicking on a button.
I managed to do it initially by copying the example on W3SCHOOL but then I tried to apply the same logic to a different button and div , and it did not work. I tried to rewrite it a little bit to work with multiple variables but I couldn’t do it on my own

Here is the code :

<button class="navbarBTN"onclick="hideshow()">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-supported-dps="24x24" fill="currentColor" class="mercado-match" width="24" height="24" focusable="false">
            <path d="M3 3h4v4H3zm7 4h4V3h-4zm7-4v4h4V3zM3 14h4v-4H3zm7 0h4v-4h-4zm7 0h4v-4h-4zM3 21h4v-4H3zm7 0h4v-4h-4zm7 0h4v-4h-4z"></path>
          </svg></button>
          <div class="myDIV" class="flex-column bg-light rounded-3" style="position: absolute;  width: 180px; font-size: smaller; margin-top: 2.5%;">
            <div class="d-flex flex-column">
              <ul style="margin: 0; padding: 6px; border-color:#666666; border-bottom: 2px solid;">
                <p class="m-0">Costin Velicu</p>
                <p class="fw-light">Looking for work</p>
                <button type="button" class="btn btn-outline-primary rounded-5" style="width: 100%; height: 30px;"><p style="font-size: smaller;">View profile</p></button>
              </ul>
</div>   

<script>
function hideshow() {
  var x = document.getElementsByClassName("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

This one works
Essentially after I press the button the div switches display mode from block to none.

<button class="navbarBTN"onclick="hideshow()">
          <div class="d-flex sticky-bottom bg-light" style="width: fit-content; left: 80%; position: relative;">
            <i class="fa-solid fa-user-ninja" style="color: #424242; font-size: larger; margin-right: 0.5em; padding: 2px"></i>
          <p style="margin-right: 10em;">Messaging</p>
          <div class="justify-content-between"><i class="fa-solid fa-ellipsis" style="color: #424242; margin-right: 0.5em;"></i><i class="fa-solid fa-pen-to-square" style="color: #424242; margin-right: 0.5em;"></i><i class="fa-solid fa-angle-up" style="color: #424242; margin-right: 
          0.5em;"></i></div></div></button>
        <div class="myDIV" style="display: flex; flex-direction: column-reverse; position: relative; left: 80%;">
         <div class="container d-flex flex-column bg-light-subtle" style="width: 350px; position: absolute;">
          <form class="d-flex">
            <input class="form-control me-1" type="search" placeholder="Search..." aria-label="Search">
            </form>
<script>
function hideshow() {
  var x = document.getElementsByClassName("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
        
     

This one doesn’t work.

Load images with hash in the filename

I am having a problem on loading images. Because it seems an hash is being appended to the filename ( for cache issues I believe)

So I have a image in src/assets/images/image.png directory

In my component I am loading the image this way:

import image from '../assets/images/image.png';

and using like this

<img src={image} ... />

When I console.log(image) I see /static/media/image.f8472220a57d9ac1591b.png.

From what I read I need to add the package file-loader to the project and configure the webpack.config.js.
However I dont see that file. But I see the a file .eslintrc.json and tsconfig.json.

In the file .eslintrc.json I added this block inside of rules{}

rules: {
...
"loader": {
      "test": ["*.png", "*.jpeg", "*.jpg", "*.gif"],
      "use": ["file-loader"],
      "exclude": "/node_modules",
      "options": {
        "name": "static/media/[name].[hash:8].[ext]"
      }
    }
}

And it seems to work fine. I can load the images properly.

However when I start the project (yarn start) I see this kind of error

enter image description here

Then I update some code and the error vanish away xD

Is there any way I can prevent this inital error? How can I improve this rule?

In my project I dont see any webpack file 🙁

Thanks

is there a way to access the genres element

So I am creating a netflix clone and I used TMDB API to get datas but I am facing this problem where when I try to access the data it shows undefined but when I log the json promise It shows up like this:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object

An Image format of object opened form

This is the code:

    let fetchDatas = [] // To store Json Data

    const fetchData = async () => {
        let data = await fetch(`${baseURL}?api_key=${API_KEY}`); // baseURL = 'https://api.themoviedb.org/3/genre/movie/list' && API_KEY is private.

        if (data.status === 200) {
            return await data.json();
        }
    }

    fetchDatas = fetchData();
    console.log(fetchDatas);

    fetch(`${baseURL}?api_key=${API_KEY}`)
        .then(response => response.json())
        .then(data => {
            fetchDatas = data;
        })

    console.log(fetchDatas);

When ever I use API’s this problem occures how to solve this.

I need to access the promise json data and its elements. ie: "fetchDatas['genres'] or fetchDatas.genres something like this or what ever way there is!”

so that I can implement it to my Netflix clone

Read data from external file and write to html table incl. images

Is it possible to read data from a file, for example txt, xml and so on, and write it into an html table? Different data should be read out per line in the file. For example:
Name, NameBaseID, BaseID, Code

The table should be divided as follows:
3 columns, in the first line there is a ‘Name’ in each column.
In the second line, images should appear for the names above them (the images have exactly the same name as ‘NameBaseID’ in the file to be read).
In the third line there is a button under each image that is supposed to display the ‘Code’ from the external file.
When you click on the button, the ‘Code’ is copied to the clipboard (I’ve already got this part figured out).
The fourth line consists of the 3 columns that should be joined together into one and should only contain a dividing line.

PHP is not an option here as this html should only be used for offline use. JavaScript shouldn’t be a problem here as long as no external JS files on the Internet are accessed.

I hope I was able to explain my intention well enough. I apologize for any typographical errors and thank you in advance for your help and support 🙂

Problem with animation in p5.js – FrameRate and random positions

I want to make scene where snow is falling on random places, but when I implement random for the x and y position it does not work.

Here is my p5.js code:

let snowflakeX;
let snowflakeY;
let snowflakeD;

function setup() {
  createCanvas(400, 400);
  frameRate(32)
}

function draw() {
  background("skyblue");
  // Variables
  snowflakeX = random(width);
  snowflakeY = random(height);
  snowflakeD = 5;
  // Stroke
  stroke("black");
  strokeWeight(10);
  fill("orange");
  rect(0, 300, 400, 100);
  line(0, 150, 400, 150);
  line(200, 0, 200, 300);
  // No stroke
  noStroke();
  fill("purple");
  quad(0, 0, 150, 0, 50, 400, 0, 400);
  quad(250, 0, 400, 0, 400, 400, 350, 400);
  point(snowflakeX, snowflakeY, snowflakeD);
}

Here is a link to the p5 playground if you want to see it in action and edit it: https://editor.p5js.org/HristoMihovski/sketches/oi7HLTF7c

Firstly, I tried to put a frame rate of 32. Then I tried all kind of numbers, but it didn’t work. I tried plan B, to move around the point , but no effect either. Lastly I tried making a variable let frameRate = 0.1; and then multipling it by 2 like this: frameRate *= 2; But no effect.