how to make a win function tic tac to toe js

I’m trying to make a tic-tac-toe game, but I don’t know how to implement a win system. What I mean is that I need to create a system that can detect when a player wins by filling three squares in a row. I’m not sure how to do that. Could someone please help me?

I’ve created a winConditions array where I’ve listed all the possible winning combination

playerOneInput = document.getElementById(`playerOne`)
playerTwoInput = document.getElementById(`playerTwo`)
const statusText = document.getElementById(`statusText`)
const startGameBtn = document.getElementById(`startGameBtn`)
let currentPlayer = ``
const winConditions = [
    [1, 2, 3], // Top row
    [4, 5, 6], // Middle row
    [7, 8, 9], // Bottom row
    [1, 4, 7], // Left column
    [2, 5, 8], // Middle column
    [3, 6, 9], // Right column
    [1, 5, 9], // Main diagonal
    [3, 5, 7] // Secondary diagonal
]


// Fazer a função para alterar os jogadores a cada turno

function switchPlayer() {
   if (currentPlayer === playerOneInput.value) {
       currentPlayer = playerTwoInput.value
    } else {
       currentPlayer = playerOneInput.value
    }
    statusText.textContent = `Turno de ${currentPlayer}`
}


function playerName() {
    startGameBtn.addEventListener(`click`, () => {
        if (playerOneInput.value && playerTwoInput.value) {
            currentPlayer = playerOneInput.value
            switchPlayer()
            startGameBtn.disabled = true
        } else {
            alert(`Por favor, insira os nomes dos dois jogadores`)
        }
    })

}


function clickSquare() {

    const cells = document.querySelectorAll(`.cell`)

    cells.forEach(cell => {
        cell.addEventListener(`click`, () => {
            // Verifica se a célula já está marcada
            if (cell.textContent === `` && currentPlayer) {
                let marker
            } if (currentPlayer === playerOneInput.value) {
                marker = `O`
            } else {
                marker = `X`
            }
            const span = document.createElement(`span`)
            span.textContent = marker
            if (marker === `X`) {
                span.style.color = `#FF0000`
            } else {
                span.style.color = `#0000FF`
            }



                cell.appendChild(span)
                switchPlayer()


        })
    })


}

clickSquare()
playerName()

Programming Quest-2 vr-headset with A-frame: How to point the src of a element to a video file in Internal shared storage “Movies” folder?

I’m using the Aframe library to program a Meta Quest 2 using html and javascript. I used a usb cable from my windows PC to the headset to preload a video file on to the headset’s Internal shared storage, into the preexisting “Movies” folder: “my_video_file.webm”. I have this in html:

But this gives me an http 404 not found error.

Is there a way for me to set the src attribute so that it accesses that video file stored locally?

Or is there any other way to store video files locally on the vr-headset and access them via Aframe so that I don’t have to download them from the web server?

Intentional vulnerable web application

I’m currently working on a school project that involves addressing vulnerabilities in a Java Spring Boot application with React as the frontend. However, I’ve encountered a challenge in finding suitable examples online. Most of the vulnerable applications I’ve come across on GitHub have already been fixed. Could anyone provide me with some examples of vulnerable applications that I can use for my project?

I tried already to look on git repositories, but I haven’t find nothing that is suitable for the project

next js nested route after resfresh css not working

I am building a website using NextJus in which I am using nested routes for dropdown.But there is a bug in it, when I go to the page and then refresh the page, it doesn’t work.

<Navbar.Toggle aria-controls="responsive-navbar-nav"/>
                    <Navbar.Collapse id="responsive-navbar-nav">
                        <Nav className="me-auto navbar_show" >
                            {/* about us */}
                            <NavDropdown title="About" id="collapsible-nav-dropdown">
                                <NavDropdown.Item as={Link} href="/about">About Us</NavDropdown.Item>
                                <NavDropdown.Item as={Link} href="/about/news">News Letter</NavDropdown.Item>
                                <NavDropdown.Item as={Link} href={"/about/vision"}>Vision</NavDropdown.Item>
                                <NavDropdown.Item as={Link} href={"/about/mission"}>mission</NavDropdown.Item>
                            </NavDropdown>
</Nav>
</Navbar.Collapse>
</Navbar.Toggle>

my issue’s demo video. that is link click here

so anyone suggest how fix this bug in next js and yes i use app directory.

Difficulty Adjusting CSS Properties and Hiding Elements Containing Specific Text

Description:

I’m encountering challenges with adjusting CSS properties and hiding specific elements on my website. Here are the main issues I’m facing:

  1. Adjusting CSS Properties:
  • I need to modify the CSS properties for the .mega-menu__list class on my website. Specifically, I want to change the grid-template-columns, list-style, and padding properties. I want to adjust these properties to ensure that the menu items are positioned correctly and visually appealing.
  1. Hiding Elements with Specific Text:
  • I want to hide certain elements within the .kikiki.Details-HeaderMenu-6 container that contain the text ‘outlet’.

I’ve tried several approaches, including JavaScript and CSS, but none of them seem to work as expected. Can someone provide guidance or suggest an alternative solution to address these issues effectively?

// Hide Outlet Menu Items
    const menuItems = document.querySelectorAll('.mega-menu__link');
    console.log('Total menu items:', menuItems.length);
    menuItems.forEach(menuItem => {
        if (menuItem.textContent.includes('outlet')) {
            menuItem.style.display = 'none';
            menuItem.style.width = '0';
        }
// Define the function to adjust CSS properties for the mega-menu__list class
function adjustCSSProperties() {
    const targetElement = document.querySelector('.mega-menu__list');

    if (targetElement) {
        // Adjust grid-template-columns property
        targetElement.style.gridTemplateColumns = 'repeat(4, minmax(0, 1fr))';

        // Adjust list-style property
        targetElement.style.listStyle = 'none';

        // Adjust padding property
        targetElement.style.padding = '2.4rem 0';
    } else {
        console.error('Target element .mega-menu__list not found.');
    }
}

I want to adjust these properties to ensure that the menu items are positioned correctly and visually appealing.

How to add custmo js to a scorm package

i want to add

this code for example:

document.addEventListener(“DOMContentLoaded”) … to index.html into a scorm package.

I test in sandbox mode without load into a lms platform but when i upload the scorm into lms , this js not working anymore.

How can i do this?

server side with direct link works.

How to optimize checkbox selection logic and minimize loops in React?

I’m working on a React project where I have multiple lists of items with checkboxes, similar to the checkbox selection feature in the shopping cart page of Shopee. Currently, I’ve implemented the checkbox functionality using React state and handling events for individual checkboxes and select-all checkbox.

However, I’m concerned about the performance implications, especially when dealing with a large number of lists or items. I noticed that my code involves multiple loops and wondering if there’s a better way to optimize the selection logic and minimize the use of loops.

Here’s a simplified version of my code:

import React, { useState } from 'react';

const App = () => {
  const lists = [
    { name: 'list1', items: ['a', 'b', 'c'] },
    { name: 'list2', items: ['x', 'y', 'z'] },
    { name: 'list3', items: ['1', '2', '3'] },
  ];

  const [selectedLists, setSelectedLists] = useState(() => {
    const initialSelectedLists = {};
    lists.forEach((list) => {
      initialSelectedLists[list.name] = [];
    });
    return initialSelectedLists;
  });

  const handleListCheckboxChange = (listName, listItems) => {
    const newListState = { ...selectedLists };
    const currentList = newListState[listName];
    newListState[listName] = currentList.length === listItems.length ? [] : [...listItems];
    setSelectedLists(newListState);
  };

  const handleAllListsCheckboxChange = () => {
    const newListState = {};
    const anyListUnselected = lists.some((list) => {
      const { name, items } = list;
      return selectedLists[name].length !== items.length;
    });

    lists.forEach((list) => {
      const { name, items } = list;
      newListState[name] = anyListUnselected ? [...items] : [];
    });

    setSelectedLists(newListState);
  };

  const handleListItemCheckboxChange = (listName, item) => {
    const newListState = { ...selectedLists };
    const currentList = newListState[listName];
    const itemIndex = currentList.indexOf(item);

    if (itemIndex !== -1) {
      newListState[listName] = [
        ...currentList.slice(0, itemIndex),
        ...currentList.slice(itemIndex + 1),
      ];
    } else {
      newListState[listName] = [...currentList, item];
    }

    setSelectedLists(newListState);
  };

  const allItemsSelected = (listName) => {
    const list = getListByName(listName);
    return selectedLists[listName].length === list.items.length;
  };

  const allListsSelected = () => {
    return lists.every((list) =>
      allItemsSelected(list.name)
    );
  };

  const getListByName = (listName) => {
    return lists.find((list) => list.name === listName);
  };

  return (
    <div>
      <button onClick={handleAllListsCheckboxChange}>
        {allListsSelected() ? 'Unselect All' : 'Select All'}
      </button>
      {lists.map((list) => (
        <div key={list.name}>
          <button onClick={() => handleListCheckboxChange(list.name, list.items)}>
            {allItemsSelected(list.name) ? `Unselect ${list.name}` : `Select ${list.name}`}
          </button>
          {list.items.map((item) => (
            <div key={item}>
              <input
                type="checkbox"
                checked={selectedLists[list.name].includes(item)}
                onChange={() => handleListItemCheckboxChange(list.name, item)}
              />
              {item}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
};

export default App;

code: https://codesandbox.io/p/sandbox/romantic-borg-qhngwq
I’d appreciate any suggestions or best practices to improve the performance and efficiency of the checkbox functionality, similar to how it’s implemented in Shopee’s shopping cart page

I want to reduce the loop overhead, and I’m looking for an optimal way to do it, but I’m not sure how.

Heroku NextJs trigger build when data is updated

We currently operate two applications on Heroku: a backend built with KeystoneJS 6 and a frontend using Next.js 14. Both apps are connected to Heroku through the GitHub Deployment Method, each residing in its private repository. As I focus on backend development, I aim to initiate a rebuild of the Next.js frontend whenever specific data operations occur, such as creation, update, or deletion.

I’ve successfully configured the necessary hooks for these operations on the backend. However, I’m encountering difficulties triggering a new build on the frontend application. To address this, I’ve generated a GitHub Access Token to authenticate requests.

Initially, I attempted to trigger a new build using the Heroku API with the following code

await heroku.post(`/apps/${process.env.HEROKU_APP_ID}/builds`, {
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/vnd.heroku+json; version=3',
    Authorization: `token ${process.env.GITHUB_PERSONAL_ACCESS_TOKEN}`,
  },
  body: {
    source_blob: {
      url: `https://api.github.com/repos/${repoOwner}/${repoName}/tarball/${branchName}`,
    },
  },
});

However, this approach returned an error response: body: { id: 'unauthorized', message: 'Invalid credentials provided.' }

Additionally, the Heroku Dashboard displayed the message: “Unable to fetch source from GitHub. Please ensure your GitHub connection is valid and that any GitHub security settings are configured to allow Heroku access.”

Interestingly, I discovered that the same GitHub Access Token successfully authenticated requests when directly downloading the tarball:

const tarballDownload = await fetch(
 `https://api.github.com/repos/${repoOwner}/${repoName}/tarball/${branchName}`,
 {
   headers: {
     Authorization: `token ${githubToken}`,
   },
 }
);

I’m currently seeking guidance on the correct approach to trigger a new build on the frontend application. Any insights or suggestions would be greatly appreciated.

background change animation

I have the following piece of code:

      <main class="page" id="page">
        <div class="holder">
          <div class="slide group1">
            <div class="slide__lines"></div>
            <div class="slide__inner">
              <div class="group1__bg"></div>
              <div class="group1__lines"></div>
              <div class="container">
                <div class="slide__text text-top">
                  <h1>We create <span class="gradient">IT solutions</span> that recoup investment and increase efficiency of your business</h1>
                  <a href="#contacts" class="btn">Submit</a>
                </div>
              </div>
              <div class="scroll-down">
                <div class="text">
                  <span>scroll down</span>
                  <svg viewBox="0 0 27 50" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="0.5" y="0.5" width="26" height="49" rx="13" stroke="#434758" stroke-opacity="0.5" />
                    <rect x="12.5" y="8.5" width="2" height="10" rx="1" stroke="#434758" stroke-opacity="0.5" class="line" />
                  </svg>
                </div>
              </div>
            </div>
          </div>
setTimeout(function () {
    var group1 = document.querySelector('.group1');
    var group1Text = group1.querySelector('h1');
    var group1Bg = group1.querySelector('.group1__bg');
    var submitBtn = document.querySelector('.btn');
    var slideLines = group1.querySelectorAll('.slide__lines');
    group1.classList.add('custom-color');

    group1Text.textContent = "We help businesses grow through their automation. We accelerate the internal workflows of companies, increase efficiency, minimize routine tasks, and reduce costs.";
    group1Text.classList.add('fade-in');
    group1Text.style.color = "#fff";

    group1Bg.style.opacity = '0';
    setTimeout(function () {
        group1Bg.style.background = "#1D1F23";
        group1Bg.style.opacity = '100';
        group1Bg.style.transition = "opacity 1s ease";
        group1Bg.style.backgroundImage = "url('../images/lines.svg')";
        group1Bg.style.backgroundRepeat = "no-repeat";
        group1Bg.style.backgroundSize = "cover";
        group1Bg.style.animation = "none";

        slideLines.forEach(function (slideLine) {
            slideLine.style.position = "absolute";
            slideLine.style.left = "10vw";
            slideLine.style.right = "10vw";
            slideLine.style.bottom = "0";
            slideLine.style.top = "0";
            slideLine.style.borderLeft = "1px solid #323544";
            slideLine.style.borderRight = "1px solid #323544";
            slideLine.style.zIndex = "1";
        });

        submitBtn.style.opacity = "0";
        submitBtn.style.transition = "opacity 0.5s ease";
        setTimeout(function () {
            submitBtn.style.opacity = "0";
        }, 100);

        setTimeout(function () {
            group1Bg.style.opacity = '1';
            submitBtn.style.display = "none";
            group1Bg.style.animation = "move-bg 15s linear infinite";
        }, 100);
    }, 100);
}, 5000);

This is an animation of changing the background and text, you need to make it so that it works when scrolling.
How to explain this correctly, we need that when we scroll the page it does not scroll but remains in this section, after a couple of scrolls we should have this animation play and then we can scroll through other sections, I have no ideas on how to implement this. I made a slightly different code with scrolling, but it scrolls the section, but this should not happen.

I will be grateful if someone can explain and help.

complete and fix animation

Speech-to-text functionality functions properly in the local environment but encounters network issues in the client’s environment

Speech-to-text functions smoothly in the local environment but faces network errors in the azure virtual desktop. I’ve verified all browser permissions, and everything appears to be in order. If anyone else is experiencing a similar issue, any solutions would be greatly appreciated.

my code is:

let recognition;
let isListening = false;

    function toggleSpeechRecognition() {
        if (!isListening) {
            startSpeechRecognition();
        } else {
            endSpeechRecognition();
        }
    }

    function startSpeechRecognition() {
        if (!recognition) {
            if ('webkitSpeechRecognition' in window) {
                recognition = new webkitSpeechRecognition();
            } else if ('SpeechRecognition' in window) {
                recognition = new SpeechRecognition();
            } else {
                return;
            }

            recognition.onresult = function(event) {
                const transcript = event.results[0][0].transcript;
                document.getElementById("chatInput").value = transcript;
            };

            recognition.onerror = function(event) {
                console.error('Speech recognition error:', event.error);
            };

            recognition.onend = function() {
                document.getElementById('mic_icon').style.display = 'inline';
                document.getElementById('soundwave_icon').style.display = 'none';
                var elements = document.getElementsByClassName('span-s');
                for (var i = 0; i < elements.length; i++) {
                    elements[i].style.backgroundColor = '#008d81';
                }
                isListening = false;
            };
        }
        document.getElementById('mic_icon').style.display = 'none';
        document.getElementById('soundwave_icon').style.display = 'inline';
        var elements = document.getElementsByClassName('span-s');
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.backgroundColor = 'red';
        }

        recognition.start();
        isListening = true;
    }

    function endSpeechRecognition() {
        if (recognition) {
            recognition.stop();
        }

        document.getElementById('mic_icon').style.display = 'inline';
        document.getElementById('soundwave_icon').style.display = 'none';
        var elements = document.getElementsByClassName('span-s');
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.backgroundColor = '#008d81';
        }
        isListening = false;
    }
    document.getElementById('soundwave_icon').addEventListener('click', function() {
        endSpeechRecognition();
    });

I’ve checked all browser permissions to ensure they’re configured correctly. Additionally, I’ve reviewed network settings and tested connectivity to rule out any issues on that front. However, the problem persists. I was expecting the speech-to-text feature to work smoothly in the client’s environment as it does in the local environment. If anyone has encountered a similar issue or has suggestions for troubleshooting steps, I would greatly appreciate the assistance.

Lightning Chart Bar Chart type Horizontal with axis at the bottom

I am using lightningChartJS

with a heatmap and horizontal bar chart

as seen in the image bellow

How can I make (1 in the image) the x-Axis to be at the position of bottom (2) in order to be aligned with (3)

enter image description here

this is the code I am using to initiolize the charts


const createRMSGraph = (divRef: string) => {

  const chart = lc
    .BarChart({
      container: divRef,
      theme: theme,
      type: BarChartTypes.Horizontal,
    })
    .setSeriesBackgroundFillStyle(BackgroundFill)
    .setTitle('');

  const data = [
    { category: 'Helsinki', value: 19.1 },
    { category: 'New York', value: 20.6 },  ];

  chart.setData(data);
};


const createPSDGraph = (divRef: string) => {
  //init
  const theme = Themes.light;
  const BackgroundFill = new SolidFill({
    color: ColorHEX('#ffffff'),
  });
  const chart = lc
    .ChartXY({
      container: divRef,
      theme: theme,
    })
    .setSeriesBackgroundFillStyle(BackgroundFill)
    .setTitle('');

  // add heatmap on top of 
  chart.addHeatmapGridSeries({
    columns: 1000,
    rows: 1000,
  });  
};

export { createPSDGraph };

Javascript taking over the whole page on wordpress [closed]

I’ve been creating online tools using chatgpt to write the code and making edit. But this one is taking over the entire page and displaying wrong. I’ve tried to make changes to the code but i’m still not getting it

Here is the code for reference

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Goat Fee Commission Calculator</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    .container {
      max-width: 400px;
      margin: 50px auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }
    label {
      font-weight: bold;
    }
    input[type="text"], input[type="number"] {
      width: 100%;
      padding: 8px;
      margin: 5px 0 20px 0;
      box-sizing: border-box;
    }
    button {
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    button:hover {
      background-color: #45a049;
    }
    #result {
      margin-top: 20px;
    }
  </style>
</head>
<body>

<div class="container">
  <h2>Goat Fee Calculator</h2>
  <label for="costOfItems">Cost of Items:</label>
  <input type="number" id="costOfItems" placeholder="Enter cost of items">

  <label for="listingPrice">Listing Price:</label>
  <input type="number" id="listingPrice" placeholder="Enter listing price">

  <label for="location">Select Location:</label>
  <select id="location">
    <option value="Australia">Australia</option>
    <option value="Germany">Germany</option>
    <option value="Ireland">Ireland</option>
    <option value="Belgium">Belgium</option>
    <option value="Canada">Canada</option>
    <option value="United States">United States</option>
    <option value="United Kingdom">United Kingdom</option>
    <option value="Netherlands">Netherlands</option>
    <option value="France">France</option>
    <option value="Other">Other</option>
  </select>

  <button onclick="calculateCommission()">Calculate</button>

  <div id="result"></div>
</div>

<script>
  function calculateCommission() {
    var costOfItems = parseFloat(document.getElementById('costOfItems').value);
    var listingPrice = parseFloat(document.getElementById('listingPrice').value);
    var location = document.getElementById('location').value;
    var sellerFee = getSellerFee(location);
    var commission = (listingPrice * 0.095) + sellerFee;
    var totalProfit = listingPrice - commission - costOfItems;

    document.getElementById('result').innerHTML = `
      <p>Goat Fee: $${commission.toFixed(2)}</p>
      <p>Total Profit: $${totalProfit.toFixed(2)}</p>
    `;
  }

  function getSellerFee(location) {
    switch (location) {
      case 'Australia':
        return 6;
      case 'Germany':
        return 5;
      case 'Ireland':
        return 12;
      case 'Belgium':
        return 6;
      case 'Canada':
        return 5;
      case 'United States':
        return 5;
      case 'United Kingdom':
        return 5;[text]
      case 'Netherlands':
        return 6;
      case 'France':
        return 6;
      case 'Other':
        return 5;
      default:
        return 0;
    }
  }
</script>

</body>
</html>

This is how the page displays on the website (https://randomness.app/goat-fee-calculator/). If there’s anything i can add to the code to make it display properly.

How to detect on command line whether JavaScript file has any syntax errors?

I would like to run a command to detect whether a JavaScript file has any syntax errors:

somecmd /path/to/file.js

I don’t care about linting or style checking or warnings. I simply want to know whether there are syntax errors or not. I.e. somecmd should exit with 0 if the file is ok or 1 if it isn’t.

By way of context, my JavaScript files are simple Stimulus controllers, executed in the browser as part of a Rails app. There’s no build step, no transpilation, etc.

I feel this should be simple, but the more I look into it the more confused I get. Things like eslint and jshint support endless rules and presets and so on and produce copious output. But I can’t figure out how to just get a simple yes/no to the question of whether a file is syntactically ok.

Ideally there would a standalone binary I could install rather than something which depends on node (my experience with node is that there are always version incompatibilities and it slows down my shell’s initialisation time).