Why puzzle tiles are swapping randomly rather than with just empty tile?

So here is my javascript part of Sliding puzzle project. It doesn’t seem to be checking if tiles are adjacent to empty tile before swapping. I changed code several times and now can’t see the problem. I’d appreciate any help.

let count = 0;
const body = document.body;
const puzzleOverlay = document.getElementById('puzzle-overlay'); //Create overlay when puzzle modal is open
const menuOverlay = document.getElementById('menu-overlay'); //Create overlay when menu modal is open
const modal = document.getElementById('modal'); //Get menu modal
const menuButton = document.getElementById('menu-button'); //Get the button to open menu modal
const close = document.getElementsByClassName('close-button')[0]; //Get the element that closes modal
const imgModal = document.getElementById('imgModal'); //Get complete puzzle modal
const imgButton = document.getElementById('show-img'); //Get the button to open image modal
const newGame = document.getElementById('new-game'); //Get a new game button
let movesCounter = document.querySelector('#moves'); //Get moves counter button


//Initial puzzle array
const initialPuzzle = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 0] //0 for the empty tile
];

//Check if puzzle is solved
function isPuzzleSolved() {
  let tileNumbers = [];

  //Collect the numbers of tiles
  for (let row = 1; row <= 3; row++) {
    for (let column = 1; column <= 3; column++) {
      const tile = document.getElementById('tile' + row + column);
      tileNumbers.push(parseInt(tile.textContent));
    }
  }

  //Check if tiles are in sequence
  for (let i = 0; i < tileNumbers.length - 1; i++) {
    if (tileNumbers[i] !== i + 1) {
      return false;
    }
  }

  //The last tile is an empty one
  return tileNumbers[tileNumbers - 1] === '9';
}

//Change puzzle to array
function isSolvable(puzzle) {
  const flatPuzzle = puzzle.flat();
  const size = flatPuzzle.length;

  let inversions = 0;
  for (let i = 0; i < size - 1; i++) {
    for (let j = 0; j < size; j++) {
      if (flatPuzzle[i] !== 0 && flatPuzzle[j] !== 0 && flatPuzzle[i] > flatPuzzle[j]) {
        inversions++;
      }
    }
  }

  return inversions % 2 === 0;
}

//Atach event listeners to tiles
document.addEventListener('DOMContentLoaded', function() {
  newGame.addEventListener('click', function() {
    shufflePuzzle();
    count = 0;
    movesCounter.innerHTML = 'Moves: ' + count;
  });

  for (let row = 1; row <= 3; row++) {
    for (let column = 1; column <= 3; column++) {
      const tile = document.getElementById('tile' + row + column);
      tile.addEventListener('click', (function(currentRow, currentColumn) {
        return function() {
          chooseTile(currentRow, currentColumn);
          moveTiles('tile' + currentRow + currentColumn, 'tile33');

          //Check if puzzle is solved
          if (isPuzzleSolved()) {
            alert('Congratulations! You solved the puzzle!');
          }
        };
      })(row, column));
    }
  }
});

function moveTiles(tile1, tile2) {
  const tile1Element = document.getElementById(tile1);
  const tile2Element = document.getElementById(tile2);

  // Swap the src attribute of the two tiles
  const tempSrc = tile1Element.src;
  tile1Element.src = tile2Element.src;
  tile2Element.src = tempSrc;

  // Swap data attributes to update tile positions
  [tile1Element.dataset.row, tile2Element.dataset.row] = [tile2Element.dataset.row, tile1Element.dataset.row];
  [tile1Element.dataset.column, tile2Element.dataset.column] = [tile2Element.dataset.column, tile1Element.dataset.column];

  //Count moves
  count++;
  movesCounter.innerHTML = 'Moves: ' + count;
}

//Nested loops for each cell of the table
function shufflePuzzle() {
  if (!isSolvable(initialPuzzle)) {
    alert('Puzzle is not solvable! Please start new game!');
    return;
  }

  document.getElementById('moves').innerHTML = 'Moves: 0';

  for (let row = 1; row <= 3; row++) {
    for (let column = 1; column <= 3; column++) {

      let secondRow = Math.floor(Math.random() * 3 + 1);
      let secondCol = Math.floor(Math.random() * 3 + 1);

      if (row !== secondRow || column !== secondCol) {
        const tile1 = "tile" + row + column;
        const tile2 = "tile" + secondRow + secondCol;
        moveTiles(tile1, tile2);
      }
    }
  }
}

newGame.addEventListener('click', shufflePuzzle);

function chooseTile(row, column) {
  const tile = document.getElementById("tile" + row + column);
  const tileClass = tile.className;

  // Get the positions of the adjacent tiles
  const leftTile = document.getElementById("tile" + row + (column - 1));
  const rightTile = document.getElementById("tile" + row + (column + 1));
  const topTile = document.getElementById("tile" + (row - 1) + column);
  const bottomTile = document.getElementById("tile" + (row + 1) + column);

  // Check if any adjacent tile is the empty tile
  const isLeftEmpty = leftTile && leftTile.className.includes("tile9");
  const isRightEmpty = rightTile && rightTile.className.includes("tile9");
  const isTopEmpty = topTile && topTile.className.includes("tile9");
  const isBottomEmpty = bottomTile && bottomTile.className.includes("tile9");

  // Check if the current tile can be moved
  if (tileClass.includes("tile9") && (isLeftEmpty || isRightEmpty || isTopEmpty || isBottomEmpty)) {
    if (isLeftEmpty) {
      moveTiles("tile" + row + column, "tile" + row + (column - 1));
    } else if (isRightEmpty) {
      moveTiles("tile" + row + column, "tile" + row + (column + 1));
    } else if (isTopEmpty) {
      moveTiles("tile" + row + column, "tile" + (row - 1) + column);
    } else if (isBottomEmpty) {
      moveTiles("tile" + row + column, "tile" + (row + 1) + column);
    }
  } else {
    console.log(`No adjacent empty tile found for (${row}, ${column})`);
  }
}

//Open menu modal if button is clicked
menuButton.onclick = function() {
  modal.style.display = 'block';

  // Disable the body
  body.style.overflow = 'hidden';
  menuOverlay.style.display = 'block';
};

//Close menu modal when close (x) element is clicked
close.onclick = function(event) {
  modal.style.display = 'none';

  // Enable the body
  body.style.overflow = 'auto';
  menuOverlay.style.display = 'none';
};

//Open image modal if button is clicked
imgButton.onclick = function() {
  imgModal.style.display = 'block';

  // Disable the body
  body.style.overflow = 'hidden';
  puzzleOverlay.style.display = 'block';
};

//Close image modal when user clicks on image
imgModal.onclick = function(event) {
  imgModal.style.display = 'none';

  // Enable the body
  body.style.overflow = 'auto';
  puzzleOverlay.style.display = 'none';
};

movesCounter.addEventListener('click', function() {
  count += 1;
  movesCounter.innerHTML = 'Moves: ' + count;
});
<!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" />
  <meta name="description" content="Sliding 3x3 puzzle game with objective is to rearrange the tiles to make a complete image in as little moves as possible." />
  <link rel="stylesheet" href="assets/css/style.css" />
  <title>Sliding Puzzle</title>
  <link href="favicon.ico" rel="shortcut icon" type="image/x-icon" />
</head>

<body>
  <div class="container">
    <h1>Sliding Puzzle</h1>
    <!--Menu Modal-->
    <div class="menu-modal" id="modal">
      <h2 class="menu-title">Main Menu</h2>
      <span class="close-button">
          <a href="#" id="close"
            ><i
              class="fa-sharp fa-regular fa-rectangle-xmark fa-2xl"
              style="color: #2f97a0"
            ></i
          ></a>
        </span>
      <div class="sub-menu">
        <div class="menu-subtitle">Objective</div>
        <div class="menu-text">
          <p>
            Solve a puzzle by rearranging tiles in correct order to make a complete image.
          </p>
        </div>
        <div class="menu-subtitle">Rules</div>
        <div class="menu-text">
          <p>
            <span class="bold">New Game:</span> At the beginning of the game click "New Game" to shuffle the tiles.
          </p>
          <p>
            <span class="bold">Tile Movement:</span> The game is played on a grid with square tiles. There is one empty space that allows tiles to slide into it.
          </p>
          <p>
            <span class="bold">Tile Sliding:</span> Tiles can be moved horizontally or vertically into the empty space. Only one tile can occupy the empty space at a time, and tiles cannot jump over one another.
          </p>
          <p>
            <span class="bold">Winning:</span> The game is considered solved or won when the tiles are in the correct order to make a complete image.
          </p>
          <p>
            <span class="bold">Reset and Shuffle:</span> To reset the puzzle to its initial state click on "New Game" to shuffle the tiles to start over.
          </p>
          <p>
            <span class="bold">Show/ close complete puzzle:</span> To see complete puzzle image click on "Show image", to close - click on image
          </p>
        </div>
      </div>
    </div>
    <div id="menu-overlay"></div>
    <!--End of modal-->
    <div class="game-container">
      <div class="buttons">
        <!--A button to open modal-->
        <button id="menu-button">Menu</button>
        <!--New game button-->
        <button id="new-game">New Game</button>
        <!--A button to show complete puzzle image-->
        <button id="show-img">Show image</button>
        <!--Moves counter-->
        <div id="moves">Moves: 0</div>
      </div>
      <!--Complete puzzle modal-->
      <div class="complete-puzzle" id="imgModal">
        <img src="assets/images/coast-of-galway360.jpg" alt="Photo of Galway coast on a sunny day" />
      </div>
      <div id="puzzle-overlay"></div>
      <div id="puzzle-container">
        <img id="tile11" class="tile tile1" data-row="1" data-column="1" src="assets/images/1.jpg" alt="Puzzle tile with clouds" />
        <img id="tile12" class="tile tile2" data-row="1" data-column="2" src="assets/images/2.jpg" alt="Puzzle tile with clouds" />
        <img id="tile13" class="tile tile3" data-row="1" data-column="3" src="assets/images/3.jpg" alt="Puzzle tile with clouds" />
        <img id="tile21" class="tile tile4" data-row="2" data-column="1" src="assets/images/4.jpg" alt="Puzzle tile with clouds and ocean" />
        <img id="tile22" class="tile tile5" data-row="2" data-column="2" src="assets/images/5.jpg" alt="Puzzle tile with clouds and ocean" />
        <img id="tile23" class="tile tile6" data-row="2" data-column="3" src="assets/images/6.jpg" alt="Puzzle tile with clouds and ocean" />
        <img id="tile31" class="tile tile7" data-row="3" data-column="1" src="assets/images/7.jpg" alt="Puzzle tile with beach sand and rocks" />
        <img id="tile32" class="tile tile8" data-row="3" data-column="2" src="assets/images/8.jpg" alt="Puzzle tile with beach sand and rocks" />
        <img id="tile33" class="tile tile9" data-row="3" data-column="3" src="assets/images/empty-tile9.jpg" alt="Empty, white puzzle tile" />
      </div>
    </div>
    <!--Footer-->
    <footer class="footer">
      <ul class="footer-icons">
        <li>
          <a href="https://github.com/violaberg" target="_blank" rel="noopener" aria-label="Visit my GitHub page (opens in a new tab)"><i class="fa-brands fa-github fa-xl" style="color: #000000"></i
            ></a>
        </li>
        <li>
          <a href="https://www.instagram.com/photos_by_vb/" target="_blank" rel="noopener" aria-label="Visit my Instagram page (opens in a new tab)"><i
                class="fa-brands fa-instagram fa-xl"
                style="color: #000000"
              ></i
            ></a>
        </li>
        <li>
          <a href="https://www.linkedin.com/in/viola-bergere-5a668699/" target="_blank" rel="noopener" aria-label="Visit my LinkedIn page (opens in a new tab)"><i class="fa-brands fa-linkedin fa-xl" style="color: #000000"></i
            ></a>
        </li>
      </ul>
      <p class="copyright">&copy;reated by violaberg</p>
    </footer>
    <!--End of footer-->
  </div>
  <script src="https://kit.fontawesome.com/284fde1047.js" crossorigin="anonymous"></script>
  <script src="assets/js/script.js"></script>
</body>

</html>

I had working puzzle but it kept giving me console error I couldn’t fix for some reason so I change the code entirely which wasn’t very smart as know I got stuck at this error for all tiles: No adjacent empty tile found for (1, 2) I tried to change up moveTiles and ChooseTile functions but nothing seems to fix the issue.

Spent Amount Calculation Issue in Budget Tracker App

Description:

I’m encountering an issue with the spent amount calculation in my budget tracker application. I’m using React on the frontend and Express.js with SQLite3 on the backend.

In my application, I fetch budget data from the backend, along with associated expenses. Each budget has an associated array of expenses. However, when I calculate the spent amount for each budget based on its associated expenses, I’m encountering unexpected behavior.

Specifically, the spent amount is consistently showing up as 0, and the remaining amount as the initial budget amount, even though expenses exist for some budgets.

Here’s what I’ve already verified and tried:

  1. Expense Data: I’ve confirmed that the expenses fetched from the
    backend include the budgetId property and that it corresponds to the
    correct budget.

  2. Budget IDs: I’ve ensured that the id passed to the
    calculateSpentByBudget function matches the budgetId of the budget
    I’m calculating the spent amount for.

  3. Parsing of Amounts: I’ve verified that the amount property of each
    expense is parsed correctly as a number.

Debugging Attempts: I’ve added console.log statements within the reduce function in calculateSpentByBudget to inspect the data during the calculation process. However, I haven’t been able to identify the source of the issue.

I suspect there might be an issue with how I’m handling the expense data or the calculation logic, but I’m having trouble pinpointing the exact cause.

The calculation code:

const calculateSpentByBudget = (budgetId) => {
    const budgetSpent = expenses.reduce((acc, expense) => {
      if (expense.budgetId !== budgetId) return acc;
  
      // Check if expense.amount is a valid number
      const amount = parseFloat(expense.amount);
      if (!isNaN(amount)) {
        acc += amount;
      }
  
      return acc;
    }, 0);
  
    return budgetSpent;
  };

it was previously this code but it kept showing up as “Nan” for both spent and remaining

 const calculateSpentByBudget = (budgetId) => {
    const budgetSpent = expenses.reduce((acc, expense) =>{
      if(expense.budgetId !== budgetId) return acc
  
      return acc += expense.amount
    }, 0)
    return budgetSpent; 
  }

helpers.js

//formating percentages
export const formatPercentage = (amt) => {
    return amt.toLocaleString(undefined,{
      style: 'percent',
      minimumFractionDigits: 0,
    })
} 
  
  //format currency
  export const formatCurrency = (amt) => {
    return amt.toLocaleString(undefined,{
      style: 'currency',
      currency: 'USD'
    })
  }

BudgetItem Page where it is being used

const BudgetItem = ({ budget, showDelete = false }) => {
  
  const { id, name, amount, color } = budget;
  const [expenses, setExpenses] = useState([]);
  const [expensesExist, setExpensesExist] = useState(false);

  useEffect(() => {
    // Fetch expenses from your backend when the component mounts
    fetchExpense();
  }, []);

  const fetchExpense = async () => {
    try {
      const response = await fetch('http://localhost:3000/expenses');
      if (!response.ok) {
        throw new Error('Failed to fetch expenses');
      }
      const data = await response.json();
      setExpenses(data); 
      setExpensesExist(data.Length > 0);
    } catch (error) {
      console.error('Error fetching expenses:', error);
      toast.error('Failed to fetch expenses');
    }
  };


  const calculateSpentByBudget = (budgetId) => {
    const budgetSpent = expenses.reduce((acc, expense) => {
      if (expense.budgetId !== budgetId) return acc;
  
      // Check if expense.amount is a valid number
      const amount = parseFloat(expense.amount);
      if (!isNaN(amount)) {
        acc += amount;
      }
  
      return acc;
    }, 0);
  
    return budgetSpent;
  };
  
  
  const spent = calculateSpentByBudget(id);

  return (
    <div
      className="budget"
      style={{
        "--accent": color,
      }}
    >
      <div className="progress-text">
        <h3>{name}</h3>
        <p>{formatCurrency(amount)} Budgeted</p>
      </div>
      <progress max={amount} value={spent}>
        {formatPercentage(spent / amount)}
      </progress>
      <div className="progress-text">
        <small>{formatCurrency(spent)} spent</small>
        <small>{formatCurrency(amount - spent)} remaining</small>
      </div>
      {showDelete ? (
        <div className="flex-sm">
          <Form
            method="post"
            action="delete"
            onSubmit={(event) => {
              if (
                !confirm(
                  "Are you sure you want to permanently delete this budget?"
                )
              ) {
                event.preventDefault();
              }
            }}
          >
            <button type="submit" className="btn">
              <span>Delete Budget</span>
              <TrashIcon width={20} />
            </button>
          </Form>
        </div>
      ) : (
        <div className="flex-sm">
          <Link to={`/budget/${id}`} className="btn">
            <span>View Details</span>
            <BanknotesIcon width={20} />
          </Link>
        </div>
      )}
    </div>
  );
};
export default BudgetItem;

I am fetching the budgets from the dashboard page

function Dashboard() {

  const location = useLocation();
  const [budgetsExist, setBudgetsExist] = useState(false);
  const [budgets, setBudgets] = useState([]);

  useEffect(() => {
    // Fetch budgets from your backend when the component mounts
    fetchBudgets();
  }, []);

  const fetchBudgets = async () => {
    try {
      const response = await fetch('http://localhost:3000/budgets');
      if (!response.ok) {
        throw new Error('Failed to fetch budgets');
      }
      const data = await response.json();
      setBudgets(data); // Set the fetched budgets
      setBudgetsExist(data.length > 0); // Set budgetsExist based on whether budgets array is empty or not
    } catch (error) {
      console.error('Error fetching budgets:', error);
      toast.error('Failed to fetch budgets');
    }
  };


  return (
    <>
      <div className="dashboard">
        {budgetsExist ? ( // Render appropriate content based on budgetsExist
          <div className="grid-lg">
            <div className="flex-lg">
              <AddBudgetForm />
              <AddExpenseForm budgets={budgets} /> 
            </div>
            <h2>Existing Budgets</h2>
            <div className="budgets">
              {
                budgets.map((budget) => (
                  <BudgetItem key={budget.id} budget={budget} />
                ))
              }
            </div>
          </div>
        ) : (
          <div className="grid-sm">
            <p>Personal budgeting is the secret to financial freedom.</p>
            <p>Create a budget to get started!</p>
            <AddBudgetForm />
          </div>
        )}
      </div>
    </>
  );

}

export default Dashboard

Backend code for fetching the budget and expenses also the table used to create expense and budget


// Endpoint to fetch budgets
app.get('/budgets', (req, res) => {
    const sql = `SELECT * FROM budgets`;

    db.all(sql, [], (err, rows) => {
        if (err) {
            console.error('Error fetching budgets:', err);
            return res.status(500).json({ error: 'Failed to fetch budgets' });
        }
        res.status(200).json(rows); // Send the fetched budgets as JSON response
    });
});


// Endpoint to fetch expenses
app.get('/expenses', (req, res) => {
    const sql = `SELECT * FROM expenses`;

    db.all(sql, [], (err, rows) => {
        if (err) {
            console.error('Error fetching expenses:', err);
            return res.status(500).json({ error: 'Failed to fetch expenses' });
        }
        res.status(200).json(rows); // Send the fetched expenses as JSON response
    });
});

// Create expenses table if it doesn't exist
db.run(`CREATE TABLE IF NOT EXISTS expenses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    newExpense TEXT NOT NULL,
    createdAt INTEGER NOT NULL,
    newExpenseAmount REAL NOT NULL,

    budgetId INTEGER NOT NULL,
    FOREIGN KEY (budgetId) REFERENCES budgets(id)
)`, (err) => {
    if (err) {
        console.error('Error creating expenses table:', err);
    } else {
        console.log('Expenses table created successfully');
    }
});

// Create budgets table
db.run(`CREATE TABLE IF NOT EXISTS budgets (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    createdAt INTEGER NOT NULL,
    amount REAL NOT NULL,
    color TEXT NOT NULL
)`, (err) => {
    if (err) {
        console.error('Error creating budgets table:', err);
    } else {
        console.log('Budgets table created successfully');
    }
});

Could someone please review my code snippets and provide guidance on how to troubleshoot and resolve this issue?

I Apologize if the snippets are too much I just thought it would be better to provide as much as possible just not to leave anything out.

Thank you in advance for your assistance!

I am trying to add unit test to the method which includes s3 methods, how to mock and add unit test in JavaScript using jest?

I am working on a JavaScript project and it has a method including some s3 file reading function as well, and I tried to add some unit test to this method but it didn’t cover the lines. I’ll attach my unit test and code here. Please help me to write unit test for this method.

  test('readFileAsJson should return JSON data from S3', async () => {

    const mockResponse = { Body: ['{"name": "John"}'] };
    s3Service.s3Client.send = jest.fn().mockResolvedValue(mockResponse);

    const jsonData = await s3Service.readFileAsJson('test-bucket', 'test-file');

    expect(jsonData).toBeDefined();

  });

import {
  S3Client,
  GetObjectCommand,
  PutObjectCommand,
} from '@aws-sdk/client-s3';

import {
  MAX_ATTEMPTS,
  BACK_OFF_RATIO,
  INITIAL_DELAY,
  REGION,
} from '../../util/constant';

import { awsRetryConfig } from '../../helpers';

class S3Service {
  constructor() {
    const retryConfigs = awsRetryConfig({
      maxAttempts: MAX_ATTEMPTS,
      backOffRatio: BACK_OFF_RATIO,
      initialDelay: INITIAL_DELAY,
    });
    this.s3Client = new S3Client({ region: REGION, ...retryConfigs });
  }

  async readFileAsJson(bucketName, fileKey) {
    try {
      const command = new GetObjectCommand({
        Bucket: bucketName,
        Key: fileKey,
      });
      const response = await this.s3Client.send(command);
      let data = '';
      for await (const chunk of response.Body) {
        data += chunk;
      }
      const jsonData = JSON.parse(data);
      return jsonData;
    } catch (error) {
      throw new Error(error);
    }
  }
export default new S3Service();

Substitute range value of 8 cells in a different sheet with one search criteria as google app script

unfortunately, my knowledge of Google app script programming is very weak and I need help as follows:
My function to find the right row in sheet2 with the search criteria from sheet works fine and now I need help to substitute exact these founded cells in the row.
First of all the function I use

function searchAndReplace(text, sheetName) {
 const ss = SpreadsheetApp.getActiveSpreadsheet();
 const sheet2 = ss.getSheetByName("Tabellenblatt3"); //data range in this sheet
 const sheet = ss.getSheetByName("Tabellenblatt1"); // search criteria in this sheet
 const text2 = sheet.getRange("I14:R14").getValues(); //range of new values
 const textFinder = sheet2.createTextFinder(text);
 const cell = textFinder.findNext();

 const row = cell.getRow();

 sheet2
   .getRange(`A${row}:${row}`)
   .activate();

}

function runsies2(){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("Tabellenblatt1");
  const text = sheet.getRange("M9").getValue();  //search criteria in M9
  
  const sheetName = "Tabellenblatt3";
  searchAndReplace(text, sheetName)
  
}

what do I have to do, to change the cell values of the activated row in sheet2 with the cell values of text2 (Range I14:R14) from sheet

I tried something with .replaceAllWith(text2) but everything went into a fault

Sunlight with suncalc tool. I have a issue to set the sun position coordinates

I’m working on a small Three.js project that requires realistic sunlight simulation based on the sun’s position throughout the day. My application needs to adhere to specific versions of dependencies defined in my package.json, which I cannot alter.

I’ve integrated SKY from DREI, and it generally functions correctly. However, I encounter a problem when setting the sun’s position using real-world solar data. I’m using suncalc.org to obtain the sun’s altitude and azimuth for San Francisco at 8 am PST, which is Altitude: 10.30° and Azimuth: 94.72°. The issue arises when I attempt to update the sun’s position to 11 am; the sun seems to vanish from the scene entirely.

Could there be a problem with how I’m applying the altitude and azimuth values in DREI? Or might there be an issue with the way the rendering engine processes these coordinates? The goal is to create a dynamic lighting environment that adjusts the directional and point lights based on the sun’s position, allowing for accurate shadow casting.

Here is a snippet of the code where I’m setting the sun’s position :
Codesandbox

How to toggle class inside a specific child element when the parent element is clicked using vanilla javascript?

When a parent button is clicked, a class is toggled inside its child element to show or hide and when that child element is clicked it will display a loading animation for few seconds and toggle back the child element to it’s original state which is hidden.

I tried to add follow the pure vanilla JS but couldn’t get it to work properly. I have done the adding show class when the parent class is clicked but the loading animation is where I got stucked.

CSS element with position: fixed and width:100% is larger than its parent

sorry for my poorly worded previous question.

I have an element that has position:fixed and width:100%. The problem is that none of the parent elements have a fixed width. So my element is actually larger than any of its parent elements.

The implementation of my code is quite complex but I think I was able to simplify things. In the code below you will notice that the green box is larger than its parent elements.

export default function App() {
  return (
    <div
      style={{
        width: "100%",
        padding: "0px 15px",
        boxSizing: "border-box",
        height: "80px",
      }}
    >
      <div
        style={{
          width: "100%",
          border: "1px solid blue",
          height: "80px",
        }}
      >
        <div
          style={{
            width: "100%",
            border: "1px solid transparent",
            height: "80px",
          }}
        >
          <div style={{ width: "inherit", height: "25px" }}>
            <div style={{ width: "inherit", height: "25px" }}>
              <div
                style={{
                  width: "inherit",
                  position: "fixed",
                  height: "25px",
                  border: "1px solid green",
                }}
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Unknown word (CssSyntaxError) [closed]

enter image description here

How to rezolve this problem. I keep getting this error in every file that I create. This error is always marked on the first word in the code. It doesn’t affect the code but it makes me uncomfortable because it shows that it is a error even if the code is perfect.

Exporting ed25519 private key in OpenSSH Format JavaScript

I have created an ed25519 key pair using the javascript crypto library

    import crypto from 'crypto'
    import sshpk from 'sshpk'

    const keypair = crypto.generateKeyPairSync(
      'ed25519',
      {
        modulusLength: 256,
        privateKeyEncoding: { format: 'pem', type: 'pkcs8' },
        publicKeyEncoding: { format: 'pem', type: 'spki' }
      }
    )

Now I need to save the private key in openssh format.

I have tried using the sshpk library but when I try to export my private key to ‘ssh’ format, the library exports the public key not the private key.

 var sshpkKey = sshpk.parseKey(keypair.privateKey.toString(), 'ssh-private')
 console.log(sshpkKey.toString('ssh'))

outputs

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIodXPD2GDD5tcgCdsmktQux+tDM8yJhzX09V9yZn4Q6 (unnamed)

So I obviously have the wrong function call here “.toString(‘ssh’)”, but, I cannot for the life of me find the right call to export the private key into the following format.

-----BEGIN OPENSSH PRIVATE KEY-----
.
.
.
-----END OPENSSH PRIVATE KEY-----

Maybe I am using the wrong library all together?

Tried to create a chrome plugin but JS Issue of undefined query occured

I tried to make a plugin but got the issue. Trying to solve the issue. Tried multiple projects but got the issues.
Content.js

 chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
 if (request.action === "convert") {
 document.documentElement.style.filter = "grayscale(100%)";
 sendResponse({ message: "Website converted to black and white." });
  } else if (request.action === "reset") {
 document.documentElement.style.filter = "none";
 sendResponse({ message: "Website reset to original colors." });
 }
 });

popup.html

 <!DOCTYPE html>
 <html>
<head>
 <link rel="stylesheet" type="text/css" href="popup.css">
  <script src="popup.js"></script>
 </head>
  <body>
   <h1>Black & White Converter</h1>
   <button id="convertButton">Convert</button>
   <button id="resetButton">Reset</button>
  </body>
  </html>

How to add rel=”sponsored noopener” into script

I would like to ask you for help. I found this code and it is working perfect. It applies custom links to images in Elementor Pro Gallery instead of one link for the gallery. I need to add there somehow rel=”sponsored noopener”. Can somebody help please?

<script>
document.addEventListener('DOMContentLoaded', function () {

let linkedImages = document.querySelectorAll('.e-gallery-item');

let links = [
'link',
'link',
'link',
'link',
'link',
'link'
];

linkedImages.forEach((linkedImage, i) => {
if (links[i] && links[i].length > 0) {
linkedImage.style.cursor = "pointer";
linkedImage.href = links[i];
linkedImage.setAttribute('target','_blank');
}
});

});
</script>

Thanks

What are the standard methods to passing state from parent to child in React?

I’ve recently been coding my first React project and have consistently come across a problem. When I pass state to a child lets say in an empty-dependency useEffect, and then the state updates, the child does not update as well. I run into the same problem using useRef as well. My question is: is there a standard method of passing information from parent to child without running into the problem of javascript closures? Is there a way to pass a state to a component who is only interacted with once on mount and have it keep reflecting new changes?

In my problem specifically, I have a piano component with pianokey children components. I create the piano in an empty-dependency useEffect. When I want to update the pianokeys with something that doesnt need a rerender lets say information to trigger an animation, I am currently cloning the key with a different prop. This could be done with using state but closures keep bogging me down.

Why does the docs for Kaboom.js say that the polygon function say it was added in v3000.2, but v3000.2 doesn’t exist?

I was trying to make a polygon in Kaboom, to help with irregular shapes not provided by Kaboom in the regular shape functions, when I get an error stating that ‘ERROR: polygon is not defined’, even though it is clearly stated in the documentation

I don’t believe I need to provide an example, but I will, just in case.

import kaboom from "kaboom"
import "kaboom/global"

kaboom()

add([
  polygon([vec2(0), vec2(50,0), vec2(50), vec2(0,50)]),
  pos(0)
])

with the following error

ERROR: polygon is not defined
    -> code/main.ts:6:0
    -> dist/game.js:4367:3

My biggest problem is that underneath the definition, it says

Since v3000.2

in the documentation, even though v3000.2 hasn’t even been published.

Am I missing something?

Method not getting called JavaScript [closed]

Method not getting called. the values of id, and ‘checked’ when calling updateSelectedID but breakpoints indicate that id=parseInt(id) is not getting executed. Suggestions for troubleshooting?

// Id array
var poId_Checked = [];

function updateSelectedID(id, checked) {
    id = parseInt(id);
    if (checked) {
        if (!poId_Checked.includes(id)) {
            poId_Checked.push(id);
        }
    } else {
        const index = poId_Checked.indexOf(id);
        if (index !== -1) {
            poId_Checked.splice(index, 1);
        }
    }

    $('#poIdChecked').val(poId_Checked);
}

// Handle single checkbox
function selectPoIDCheckBox(id) {
    const checked = $('input.checkItem[data-id="' + id + '"]').prop('checked');
    updateSelectedID(id, checked);

    if (checked) {
        var currentPageRows = table.rows({ page: 'all' });
        // Get the checked checkboxes within those rows
        var checkedCheckboxes = currentPageRows.nodes().to$().find('input[type="checkbox"]:checked');
        var checkCheckboxes = currentPageRows.nodes().to$().find('input[type="checkbox"]');
        // Get the length of the checked checkboxes
        var checkedLength = checkedCheckboxes.length;
        var checkLength = checkCheckboxes.length;
        // Log the result to the console
        var allChecked = checkedLength === checkLength;
        $('#poIdCheckAll').prop('checked', allChecked);
    } else {
        $('#poIdCheckAll').prop('checked', false);
    }
}

Expected breakpoints to stop at parseInt, but it appears either breakpoints are not working or the method is not actually getting called.