DIV move animation doesn’t work when pixel value is stored in variable

I am trying to move a DIV to the right and have an animation setup between my CSS and Javascript file. The animation works when I have the pixel value (345px) specifically typed in. However, my intent is to have a variable supplying the pixel value.

HTML code

<div id="gameContainer">
    <div class="boxes" id="greenBox"></div>
    <div class="boxes" id="blueBox"></div>
    <div class="boxes" id="redBox"></div>
    <div class="boxes" id="yellowBox"></div>
</div>

<button class="btn btn-primary">Start</button>

CSS code

.boxes{
    transition: transform 1000ms;
}

JavaScript code

$("button").click(function(){
    //THESE 3X LINES ARE USED TO GET THE PIXEL VALUE IN A VARIABLE
    var pixelStored = document.getElementById("blueBox");
    var style = window.getComputedStyle(pixelStored);
    var leftValue = style.getPropertyValue("left");
   
    //WORKS
    $("#redBox").css({top: leftValue});

    //DOESN'T WORK
    $("#greenBox").css("transform", "translateX(leftValue)");  

    //WORKS
    $("#greenBox").css("transform", "translateX(345px)"); 
});

The move with the “#redBox” div doesn’t and isn’t supposed to animate, but it does move with the ‘leftValue’ variable supplying the pixel value of 345px. I just used that as a test to see if the 345px value would work stored in a variable.
However, with my “#greenBox” transform code it doesn’t work with the pixel value stored in the ‘leftValue’ variable. I’m assuming that this has to do with ‘leftValue’ being the wrong type???

Thanks in advance for your help!!

Anyone make this code run like slideshow?

var count = 0;
var inc = 0;
    var margin = 0;
    var itemDisplay = 0;
    if(screen.width > 990){
     itemDisplay = document.getElementsByClassName('slider-main').getAttribute('item-display-1');
     margin = itemDisplay * 5;
    }
    if(screen.width > 700 && screen.width < 990 ){
     itemDisplay = document.getElementsByClassName('slider-main').getAttribute('item-display-2');
     margin = itemDisplay * 6.8;
    }
if(screen.width > 280 && screen.width < 700){
 itemDisplay = document.getElementsByClassName('slider-main').getAttribute('item-display-3');
 margin = itemDisplay * 20;
}
var item = document.getElementsByClassName('item');
var itemleft = item.length % itemDisplay;
var itemSlide = Math.floor(item.length / itemDisplay) - 1;
for(let i=0; i<item.length; i++){
 item[i].style.width = (screen.width / itemDisplay) - margin + "px";
}
function next {
 if(inc !== itemSlide + itemleft){
  if(inc === itemSlide){
   inc = inc + itemleft;
   count = count - (screen.width / itemDisplay) * itemleft;
}
  else{
   inc++;
   count = count - screen.width;
}
};
part.style.left = - screen.width + "px";
}
function prev {
 if(inc !== 0){
  if(inc === itemleft){
   inc = inc - itemleft;
   count = count + (screen.width / itemDisplay) * itemleft;
}
  else{
   inc--;
   count = count - screen.width;
}
};
part.style.left = - screen.width + "px";
}

Why my next and prev button not work ? It not change the 1 2 3 4 left or right ? Can anyone help please ? I check the code with console.log and found that .getAttribute is returns no result then alll the code behind it not work :/

How is “undefined” implemented in JS?

Preface:

I work as a Frontend teacher. A few days ago I was teaching students to primitive types. They are already learned another languages like C/C++/C# so when we started talking about undefined one of students asked me: “What is undefined under the core?” The day before I said that JS was written on C/C++ so he wondered how do they implemented undefined type in JS? I know C/C++ but I’m not an expert in this languages

I tried to explain what is undefined in JS, how to work with it, how to get it and so on but it isn’t the answer to question. All other types are also not obvious but I can at least guess how they are implemented. He assumed that undefined is also NULL but in specific way

I tried to find some explanations in ECMAScript but can’t find any explanation. In general it just says undefined is undefined

Question:

Can please someone give an answer to the question in title?

Please explain this in two ways:

  1. In a simple form, perhaps with real-life examples. Of course, if it can be explained in simple language.
  2. in a complex way, with a small amount of C/C++ code and a detailed explanation.

Modal – Options

How can I create a modal options in JavaScript? I need to create it like the image below, so when I click on the gear, this modal opens and I can increase and decrease the volume of both the sound and the game, and then I can also close it by clicking on the X which is the exit.enter image description here

I tried in several ways, but none of them were what I expected.

if else block within for loop [duplicate]

let arr1 = ["ravi", "tom", "lois"];
let question = prompt("Enter your name");
let answer = arr1.indexOf(question);

for (let i = 0; i < arr1.length; i++) {
  if (arr1[i] === question) {
    alert(`name ${question} exists at position ${answer}`);
    break;
  } else {
    alert(`input doesn't exist !!`);
    break;
  }
}

is this the right way to check user input from JavaScript Array ?

by adding else block its getting weird!

Detect and Remove Closed Browser Tabs’ Data from LocalStorage in Angular 7

In my Angular 7 project, I’ve implemented a functionality where routing opens pages in new browser tabs, and the associated router links are stored in the browser’s LocalStorage. However, I’m facing a challenge in efficiently detecting and removing these stored router links when users close an open tab.

I need a solution that doesn’t involve implementing this condition in every component file, as there are approximately 100 files to update. Is there a recommended approach or a way to centralize this functionality across the application?

I’ve considered using a service or a global event listener to track tab closure events and manage the LocalStorage data accordingly. However, I’m unsure about the best practice in Angular 7 to implement this without extensive changes to multiple files.

Any insights, examples, or guidance on achieving this in a scalable and maintainable manner across the application would be highly appreciated.

I tried @HostListener.

How to download a torrent file? node js

I used the node-torrent library.
But it gives the following error and does not download the file to the end.
When I clear this error, the downloading of the file stops, most likely another solution is needed for this error.
Please tell me, I havenโ€™t been able to find a solution for three days now.

var Client = require('node-torrent');
var client = new Client({logLevel: 'DEBUG'});
var torrent = client.addTorrent('lakeside-v0_8_7_rar.torrent');

// when the torrent completes, move it's files to another area
torrent.on('complete', function() {
    console.log('complete!');
    torrent.files.forEach(function(file) {
        var newPath = '/new/path/' + file.path;
        fs.rename(file.path, newPath);
        // while still seeding need to make sure file.path points to the right place
        file.path = newPath;
    });
});

(node:13116) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 5 complete listeners added to [Piece]. Use emitter.setMaxListeners() to increase limit
enter image description here

I tried other libraries, but they all didn’t work ๐Ÿ™
The only thing that worked was node-torrent, but not completely ๐Ÿ™
enter image description here

Virtual mouse as joystick on esp-32 communicating over WiFi

Theres this app, remotemouse, that displays a trackpad and keyboard, sends data from those over WiFi and moves the mouse or writes text on a pc. I want to implement something similar, but with an esp-32 instead of a phone and a joystick instead of a trackpad.

I already have a (kind of) working version.

I implemented communication using websockets. I transmitted the joystick data on the esp and processed it on the pc. I then used the robotjs library to use this data for mouse movement.

I expected the mouse to move smoothly and almost instantly in relation to my joystick inputs, but it was a bit choppy and delayed.

The esp code, programmed with C++ and platformIO and running as a server:

#include <Arduino.h>
#include <WiFi.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>

#include "modules/joystick/rjc_joystick.h"

WiFiClient wifi_client;
WebSocketsServer websocket = WebSocketsServer(81);

static const char*  SSID           = "MY_SSID";
static const char*  PASSWORD       = "MY_PASSWORD";

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
    // Handle events here
}

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);
  Serial.println("Connecting to WiFi ");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.printf("WiFi connected, IP: %sn", WiFi.localIP().toString().c_str());
  websocket.begin();
}

void loop() {
  JoystickPosition joystick_position = RJC_JOYSTICK::get_mapped_position(-10, 10);

  // Example: Send joystick position over WebSocket when the joystick is moved
  if (joystick_position.x != 0 || joystick_position.y != 0) {
    // Create a JSON document
    StaticJsonDocument<100> jsonDocument;

    // Populate the JSON document
    jsonDocument["type"] = "cursor";
    jsonDocument["data"]["x"] = joystick_position.x;
    jsonDocument["data"]["y"] = joystick_position.y;

    // Serialize the JSON document to a String
    String message;
    serializeJson(jsonDocument, message);

    // Send the message to all connected clients
    websocket.broadcastTXT(message);

    Serial.println("Sent joystick position over WebSocket: " + message);
  }

  websocket.loop();
  delay(35);
}

The back-end pc code programmed with nodejs and running as a client:

let WebSocketClient = require('websocket').client;
const robot = require('robotjs');

let client = new WebSocketClient();

client.on('connect', function(connection) {
  console.log('WebSocket Connected');
  connection.on('error', function(error) {
      console.log("Connection Error: " + error.toString());
  });
  connection.on('close', function() {
      console.log('Connection Closed.');
  });
  connection.on('message', function(message) {
    if (typeof message.utf8Data === 'string') {
        try {
          const data = JSON.parse(message.utf8Data);

          const type = data.type;
          const x = data.data.x;
          const y = data.data.y;

          if(type == "cursor") {
            moveMouseWithJoystick(x, y);
          } else if (type == "scroll") {
            robot.scrollMouse(x, y);
          }

          console.log(`[ws]: ${type}: ${x}, ${y}`);
        } catch (error) {
          console.error('Error parsing JSON:', error);
        }
      } else {
        console.error('Received non-string data:', message.utf8Data);
      }
  });
});

client.connect('ws://192.168.1.104:81/');

function moveMouseWithJoystick(x, y) {
  let pos = robot.getMousePos();
  pos.x += x + 5;
  pos.y += y + 5;
  robot.moveMouse(pos.x, pos.y);
}

Later other group members will write a front end for this as well.
You can look at the complete code here.

Should I be using something other than websockets? I know BLE works (I have working version of this), but I would like to communicate over WiFi because I also plan on adding other WiFi related features later, and connecting the device to a client through multiple protocols doesn’t seem great for user experience.

I implemented communication using websockets. I transmitted the joystick data on the esp and processed it on the pc. I then used the robotjs library to use this data for mouse movement.

I expected the mouse to move smoothly and almost instantly in relation to my joystick inputs, but it was a bit choppy and delayed.

Thanks for any help!

Responsive table with changing column count

I have an eight-by-eight table. Every column must have the width of the widest column. If the table doesn’t fit to page, it must be divided by two and the other half of the table must go below. This must be repeated until there is only one column left. Every time the page is resized, the column count must be calculated again.

All I could do was making a four-by-four table that reduces its column count to one if the page width is too small to fit everything. I am using Bootstrap.

Thank you very much in advance.

Tiktok like scrolling for sections

**I have recipes(sections) displayed on my page like this: **
CSS:

@media only screen and (max-width: 550px) {
    .recipe {
        background-color: whitesmoke;
        border: hidden;
        border-radius: 1rem;
        width: 100%;
        display: inline;
        text-align: center;
    }
    section h2{
        font-size: 2.2rem;
    }
    section h5{
        font-size: 1.35rem;
    }
    #container {
        white-space: nowrap;
    }
    input[type=text]{
        width: 80%;
        text-align: center;
        margin-top: 0;
    }
    h3{
        font-size: 1.6rem;
    }
    p{
        font-size: 1.25rem;
    }
    html  {
        scroll-snap-type: y mandatory;
      }
    .recipe {
 
        scroll-snap-align: start; 
    }

}

HTML:

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="../css/homepage.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
    <title>MyCookBook</title>
  </head>
    <body>
        <header>
            <div class="header">
                <h1>MyCookBook</h1>
                <input type="text" placeholder="Search..">
             <!--   <button type="submit"><span class="material-symbols-outlined">account_circle</span></button> -->
            </div>
        </header>
        <div id="container">
            <section class="recipe">
                <h2 class="recipe_elmnt">Commodo</h2>
                <h5 class="recipe_elmnt">dignissim</h5>
                <img src="../resources/placeholder_img.jpg" alt="recipe outcome photo"  class="recipe_elmnt">
                <div class="ingredients">
                    <h3>Ingredients</h3>
                    <ul>
                        <li><p>eget duis at</p></li>
                        <li><p>eget duis at</p></li>
                        <li><p>eget duis at</p></li>
                    </ul>
                </div>
                <div class="procedure">
                    <h3>Procedure</h3>
                    <ul>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                    </ul>
                </div>
            </section>
            <section class="recipe">
                <h2 class="recipe_elmnt">Commodo</h2>
                <h5 class="recipe_elmnt">dignissim</h5>
                <img src="../resources/placeholder_img.jpg" alt="recipe outcome photo" class="recipe_elmnt">
                <div class="ingredients">
                    <h3>Ingredients</h3>
                    <ul>
                        <li><p>eget duis at</p></li>
                        <li><p>eget duis at</p></li>
                        <li><p>eget duis at</p></li>
                    </ul>
                </div>
                <div class="procedure">
                    <h3>Procedure</h3>
                    <ul>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                    </ul>
                </div>
            </section>
            <section class="recipe">
                <h2 class="recipe_elmnt">Commodo</h2>
                <h5 class="recipe_elmnt">dignissim</h5>
                <img src="../resources/placeholder_img.jpg" alt="recipe outcome photo" class="recipe_elmnt">
                <div class="ingredients">
                    <h3>Ingredients</h3>
                    <ul>
                        <li><p>eget duis at</p></li>
                        <li><p>eget duis at</p></li>
                        <li><p>eget duis at</p></li>
                    </ul>
                </div>
                <div class="procedure">
                    <h3>Procedure</h3>
                    <ul>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                        <li><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt 
                            ut labore et dolore magna aliqua. Quam quisque id diam vel quam elementum pulvinar.</p></li>
                    </ul>
                </div>
            </section>
        </div>
        <footer>
        </footer>
    </body>
</html>

I want to make the section(.recipe) scroll like on TikTok, where you can only see one video on the screen, and when you scroll you see the next one, etc. etc. when the viewport is smaller than 500px(or on a mobile device). I have tried the page-snap-* css property but for some reason, it didn’t work. Could anyone help?

Sort arrays in an array by string using custom alphabet in JS

I have this array:

[
    ["ik", "p", "I; me", 1],
    ["pat", "pre", "plus", 1],
    ["qeol", "adj", "only", 1],
    ["nei", "adj", "not", 1]
]

I want to sort the array alphabetically by the first item, and using a custom alphabet where q is between n and o instead.

So, it should look something like:

[
    ["ik", "p", "I; me", 1],
    ["nei", "adj", "not", 1],
    ["qeol", "adj", "only", 1],
    ["pat", "pre", "plus", 1]
]

I tried this and tried to tweak it so that the q to go between the n and o, but nothing worked.

How do I do this?

how to make document.writeln(1) not erase elements [duplicate]

When i am running JS script with document.writeln this erases all my objects on site.
I don’t see any input and buttons. What am I doing wrong?

How to fix that? It displays me just Welcome to WebOS? I don’t see any button and input

document.writeln("Welcome to WebOS!")
let command = document.getElementById("getCommand").value()
void run() {
  while (true) {
    if (document.getElementById("getCommand").value() != command) {
      command = document.getElementById("getCommand").value()
      if (command == "exit") {
        break
      }
    }
  }
}
html {
  background-color: black;
  color: white;
}

.main {
  background-color: black;
  color: white;
}

.getCommandInput {
  display: block;
  left: 250px;
}

.btn {
  display: block;
  left: 300px;
}
<div class="main">
  <script src="js/OS.js"></script>
  <input id="getCommand" class="getCommandInput" type="text" maxlength="512" />
  <button onclick="run()" class="btn">Run</button>
</div>

Validate with joi strings array or object array

I need to find a way to validate array to be or strings array or object array of some schema bit not both.

This is what I did. Is there any other clean way?

Joi.object({
    barcodes: Joi.array()
        .min(1)
        .max(4)
        .items(Joi.alternatives().try(
            Joi.string(),
            taskInternalMetadataPayload,
        ).error(new Error(errorMessage)))
        .custom(checkArrayHasSameItemType)
        .unique()
        .unique('scannedLoadId')
        .messages({
            'array.unique': 'Scanned barcodes needs to be different',
        }),
})