onchange package keeps rerun when there is not file change in my watched folder

I use onchange package to watch my src folder, tigger rebuild when change happened, however, it will always tigger several builds, the can settle down.
i asked copilot. it says I need to add a delay, but not working
and it also says, I need to check if my build will generate new files under src, but it doesn’t. so now I don’t know why.
beside, first I used nodemon, it don’t work either

 "watch": "onchange 'src/**/*.{ts,tsx}' --delay 100 -- npm run build"

my source code is in src folder, and my built stuff is all in dist folder

How to Integrate a Slider Inside an Invisible Container Toggled by a Button?

As someone relatively new to HTML, CSS, and JavaScript, I’m currently working on a learning project where I’m trying to include a slider component within a container that remains invisible by default and becomes visible only when a button is pressed. I found a tutorial on YouTube (here is the source code for it) and followed the steps to integrate the slider into my page.

The issue I’m facing is that the slider functions perfectly when I place it directly within the body of the page. However, when I attempt to nest it inside an overlay container (although I’m not entirely sure if overlay is the correct term to use here), it doesn’t seem to behave as expected.

Here is the code I want to merge from the tutorial


<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" />
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      .container {
        margin: 0 auto;
        width: 60%;
        height: 400px;
        position: relative;
        overflow: hidden;
      }

      .slides {
        display: flex;
        height: 100%;
      }

      .slide {
        min-width: 100%;
        position: relative;
      }

      .slide img {
        width: 100%;
        height: 100%;
      }

      .slide-controls {
        position: absolute;
        top: 50%;
        left: 0;
        transform: translateY(-50%);
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      #next-btn,
      #prev-btn {
        cursor: pointer;
        background: transparent;
        font-size: 30px;
        border: none;
        padding: 10px;
        color: white;
      }

      #next-btn:focus,
      #prev-btn:focus {
        outline: none;
      }

      .slide-content {
        position: absolute;
        top: 50%;
        left: 50px;
        transform: translateY(-50%);
        font-size: 60px;
        color: white;
      }
    </style>
    <title>Infinite Slideshow : non-degree programmer</title>
  </head>

  <body>
    <div class="container">
      <div class="slides">
        <div class="slide">
          <!-- <img src="img/slide-1.jpg" alt="" /> -->
          <div class="slide-content">
            <h1>slide-1</h1>
          </div>
        </div>
        <div class="slide">
          <!-- <img src="img/slide-2.jpg" alt="" /> -->
          <h1>slide-2</h1>
        </div>
        <div class="slide">
          <!-- <img src="img/slide-3.jpg" alt="" /> -->
          <h1>slide-3</h1>
        </div>
        <div class="slide">
          <!-- <img src="img/slide-4.jpg" alt="" /> -->
          <h1>slide-4</h1>
        </div>
      </div>
      <div class="slide-controls">
        <button id="prev-btn">
          <i class="fas fa-chevron-left"></i>
        </button>
        <button id="next-btn">
          <i class="fas fa-chevron-right"></i>
        </button>
      </div>
    </div>
    <script>
      const slideContainer = document.querySelector('.container');
      const slide = document.querySelector('.slides');
      const nextBtn = document.getElementById('next-btn');
      const prevBtn = document.getElementById('prev-btn');
      const interval = 3000;

      let slides = document.querySelectorAll('.slide');
      let index = 1;
      let slideId;

      const firstClone = slides[0].cloneNode(true);
      const lastClone = slides[slides.length - 1].cloneNode(true);

      firstClone.id = 'first-clone';
      lastClone.id = 'last-clone';

      slide.append(firstClone);
      slide.prepend(lastClone);

      const slideWidth = slides[index].clientWidth;

      slide.style.transform = `translateX(${-slideWidth * index}px)`;

      console.log(slides);

      const startSlide = () => {
        slideId = setInterval(() => {
          moveToNextSlide();
        }, interval);
      };

      const getSlides = () => document.querySelectorAll('.slide');

      slide.addEventListener('transitionend', () => {
        slides = getSlides();
        if (slides[index].id === firstClone.id) {
          slide.style.transition = 'none';
          index = 1;
          slide.style.transform = `translateX(${-slideWidth * index}px)`;
        }

        if (slides[index].id === lastClone.id) {
          slide.style.transition = 'none';
          index = slides.length - 2;
          slide.style.transform = `translateX(${-slideWidth * index}px)`;
        }
      });

      const moveToNextSlide = () => {
        slides = getSlides();
        if (index >= slides.length - 1) return;
        index++;
        slide.style.transition = '.7s ease-out';
        slide.style.transform = `translateX(${-slideWidth * index}px)`;
      };

      const moveToPreviousSlide = () => {
        if (index <= 0) return;
        index--;
        slide.style.transition = '.7s ease-out';
        slide.style.transform = `translateX(${-slideWidth * index}px)`;
      };

      slideContainer.addEventListener('mouseenter', () => {
        clearInterval(slideId);
      });

      slideContainer.addEventListener('mouseleave', startSlide);
      nextBtn.addEventListener('click', moveToNextSlide);
      prevBtn.addEventListener('click', moveToPreviousSlide);

      startSlide();
    </script>
  </body>

</html>

Here is my initial HTML page (index.html):


<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <link rel="stylesheet" type="text/css"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>

  <body>
    <div id="question-container">
      <input type="search" id="question-input" placeholder="ask your question" required>
      <button id="submit-button" disabled>
        <i class="fa-solid fa-magnifying-glass"></i>
      </button>
    </div>
    <div id="answer-container">
      <div id="answer"></div>
      <div id="clear-button-container">
        <button id="clear-button">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>
    </div>
    <div class="fab-container">
      <div class="fab fab-icon-holder">
        <i class="fa-solid fa-chevron-up"></i>
      </div>

      <ul class="fab-options">
        <li id="explore">
          <span class="fab-label">questions list</span>
          <div class="fab-icon-holder">
            <i class="fa-solid fa-list"></i>
          </div>
        </li>
        <li id="about">
          <span class="fab-label">about</span>
          <div class="fab-icon-holder">
            <i class="fa-regular fa-address-card"></i>
          </div>
        </li>
      </ul>
    </div>
    <div class="overlay" id="overlay">
      <div id="closeBtn">
        <i class="fa-regular fa-circle-xmark"></i>
      </div>
      <div class="explore-content" id="explore-content">
        <!-- Slider HTML -->
        <p>I want the slider to be here</p>
        <!-- End of Slider HTML -->
      </div>
      <div class="about-content" id="about-content">
        <!-- Your content goes here -->
        <p>This is the about section.</p>
      </div>
    </div>
    <script src="script.js"></script>
  </body>

</html>

Here is the initial CSS (style.css):


* {
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  /*font-size: 2em;*/
  direction: rtl;
  font-family: Arial, sans-serif;
  color: #444444;
  height: 100vh
}

#answer-container {
  position: absolute;
  top: 80%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  visibility: hidden;
  max-width: 80%;
  width: auto;
  transition: opacity 1.15s ease, top 1.15s ease;
}

#question-container {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 65%;
  height: auto;
  transition: opacity 1s ease, top 1s ease;
}

#question-input {
  width: 80%;
  max-width: 90%;
  padding: 10px;
  font-size: 16px;
  box-sizing: border-box;
  word-wrap: break-word;
  resize: none;
  height: auto;
  border: 1px solid #ccc;
}

#submit-button {
  padding: 10px 20px;
  font-size: 16px;
  margin-top: 10px;
}

#clear-button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

#clear-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: rgb(185, 28, 28);
  color: white;
  border: none;
  cursor: pointer;
}

#clear-button:hover {
  background-color: rgb(172, 26, 26);
}

#submit-button:enabled {
  cursor: pointer;
  background-color: rgb(28, 185, 62);
  color: white;
}

#answer {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

@media screen and (max-width: 600px) {
  #question-input {
    width: 90%;
  }
}

.fab-container {
  position: fixed;
  bottom: 50px;
  left: 50px;
  z-index: 997;
  cursor: pointer;
}

.fab-icon-holder {
  width: 50px;
  height: 50px;
  border-radius: 100%;
  background: #016fb9;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

.fab-icon-holder:hover {
  opacity: 0.8;
}

.fab-icon-holder i {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #fff;
}

.fab {
  width: 60px;
  height: 60px;
  background: #016fb9;
}

.fab-options {
  list-style-type: none;
  margin: 0;
  position: absolute;
  bottom: 70px;
  left: 0;
  opacity: 0;
  transition: all 0.5s ease;
  transform: scale(0);
  transform-origin: 20% bottom;
}

.fab:hover+.fab-options,
.fab-options:hover {
  opacity: 1;
  transform: scale(1);
}

.fab-options li {
  display: flex;
  justify-content: flex-end;
  padding: 5px;
}

.fab-label {
  padding: 2px 5px;
  align-self: center;
  user-select: none;
  white-space: nowrap;
  border-radius: 3px;
  font-size: 16px;
  background: #666;
  color: #fff;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
  margin-left: 10px;
}

.overlay {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0);
  /* Initially transparent */
  z-index: 998;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.5s ease;
  /* Smooth transition effect */
  display: none;
  /* Initially hidden */
}

.overlay.active {
  background-color: rgba(0, 0, 0, 0.7);
  /* Semi-transparent background */
  opacity: 1;
  /* Display when active */
}

.explore-content,
.about-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  display: none;
  /* Initially hidden */
  z-index: 999;
  color: black;
  width: 90%;
  /* Set the width to 80% of the screen */
  height: 50%;
  /* Set the width to 80% of the screen */
}

#closeBtn {
  position: absolute;
  top: 20px;
  right: 20px;
  cursor: pointer;
}

.fa-circle-xmark {
  font-size: 32px;
  color: white;
}

Initial Javascript (script.js):


const questionContainer = document.getElementById('question-container');
const answerContainer = document.getElementById('answer-container');
const questionInput = document.getElementById('question-input');
const answerDiv = document.getElementById('answer');
const submitButton = document.getElementById('submit-button');
const clearButton = document.getElementById('clear-button');
const exploreButton = document.getElementById('explore');
const aboutButton = document.getElementById('about');
const overlay = document.getElementById("overlay");
const closeBtn = document.getElementById('closeBtn');
const exploreContent = document.getElementById('explore-content');
const aboutContent = document.getElementById('about-content');

questionInput.addEventListener('input', function () {
    submitButton.disabled = !questionInput.value;
});

function handleAnswerSubmission() {
    showAnswer();
    questionInput.disabled = true;
    submitButton.disabled = true;
}

function showAnswer() {
    const question = questionInput.value;
    const answer = question;
    answerDiv.innerText = answer;
    questionContainer.style.opacity = '.5';
    questionContainer.style.top = '20%';
    answerContainer.style.opacity = '1';
    answerContainer.style.top = '50%';
    answerContainer.style.visibility = 'visible';
    submitButton.disabled = false;
}

function fetchData() {
    // const apiUrl = '';
}

function handleClear() {
    const question = questionInput.value;
    questionContainer.style.opacity = '1';
    questionContainer.style.top = '40%';
    answerContainer.style.opacity = '0';
    answerContainer.style.top = '80%';
    answerContainer.style.visibility = 'visible';
    questionInput.value = question;
    questionInput.disabled = false;
    submitButton.disabled = false;
    questionInput.focus();
}

submitButton.addEventListener('click', handleAnswerSubmission);
questionInput.addEventListener('keypress', function (e) {
    if (e.key === 'Enter' && questionInput.value && !overlay.classList.contains('active')) {
        handleAnswerSubmission();
    }
});

clearButton.addEventListener('click', handleClear);
document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && !overlay.classList.contains('active')) {
        handleClear();
    }
});

window.addEventListener('load', function () {
    fetchData();
});

exploreButton.addEventListener('click', function () {
    showOverlay(exploreContent);
});

aboutButton.addEventListener('click', function () {
    showOverlay(aboutContent);
});

closeBtn.addEventListener('click', () => {
    hideOverlay();
});


function showOverlay(content) {
    overlay.style.display = 'flex'; // Display the overlay
    overlay.classList.add('active'); // Add the active class to start transition

    // Hide all content initially
    exploreContent.style.display = 'none';
    aboutContent.style.display = 'none';

    // Show the corresponding content
    content.style.display = 'block';
}

function hideOverlay() {
    overlay.classList.remove('active');
    setTimeout(() => {
        overlay.style.display = 'none';
        exploreContent.style.display = 'none'; // Hide the content
        aboutContent.style.display = 'none'; // Hide the content
    }, 500); // Adjust this time to match the CSS transition duration
}

Parent, child component state sharing and render

    import MyModal from './MyModal';
    class Detail extends React.Component {
        constructor(props) {
        }
        return (
                <>
                    <div>
                    <MyModal
                    />
                    
                <>
                )
            }
    export default React.memo(
        connect(mapStateToProps, mapDispatchToProps)(withRouter(Detail))
    );
    
    
    export class DetailSection extends React.Component {
        constructor(props) {
        ...
        }
        async initialStateSetting() {
            await this.setState({
                physician_filter: rowData.value,
                });
    }
    }
    export default connect(
        mapStateToProps,
        mapDispatchToProps
    )(withRouter(DetailSection));
    
    
    const MyModal = (
        props   
    ) => {
        const redux_store = useSelector((state) => state); 
        }
         return (
            <>   
          
              <Modal>
               <Modal.Body>
                    <DetailSection/>
                </Modal.Body>
            <>
            )
        }
        export default MyModal;

When I click on a datagrid row, the Detail component is rendered. Inside the Document is a menu item which when clicked renders the functional component MyModal.
MyModal has a DetailSection component which does initialStateSetting processing after the MyModal useeffect runs and Mymodal is rendered. But I need the physician_filter which is inside the state of Detailsection.
I need to access physician_filter inside the MyModal. How to get physician_filter to propogate to MyModal? This is a property inside the DetailSection

Sequelize Included model’s where clause is ignored

I have a issue where i’m passing in a where clause into a included associated model and the where clause is ignored. Below is smaller sample of what i have since i can’t post the actual columns and data, but the generated sql looks to have everything except the where clause for the TableC is missing. Pretty sure the associations are working fine since i have other queries and other code where they work perfectly together, it’s simply just this one condition not working… Table C has a FK with Table A (e.g. table c has a column tableAId with a fk with the id for that table)

await TableA.findAll({
  where: {
    id: 1
  },
  include: [
    {
      model: TableB 
    },
    {
      model: TableC,
      where: {
        foo: 'bar'
      }
    }
  ],
});

Did I use this JS variable correctly in the html document?

<head>
  <script>
    var bgcolor = #ff0000
  </script>
</head>
<body style="background-color: var(--bgcolor);">
</body>

I want to make a JS function which would change the background color on certain input. I’m playing around with JS functions, and I can’t get the “var” to work in the HTML file. Can somebody check my code for correctness?

Can’t pass generic props to function component (Type is not assignable to type IntrinsicAttributes & P)

I have the following function:

export default function Hidable<P>(Component: React.FC<P>) {
  return function Wrapped(props: P & { hidden: boolean }) {
    const { hidden, ...rest } = props;

    return hidden ? null : <Component {...rest} />;
  };
}

However, I’m receiving the following error:

Error message

The weird thing is that, every other function that uses this one has the typing working perfectly:

Function using Hidable function

Function using base function

The following works:

export default function Hidable<P>(Component: React.FC<P>) {
  return function Wrapped(props: P & { hidden: boolean }) {
    return props.hidden ? null : <Component {...props} />;
  };
}

However, what I’m trying to achieve is having the behavior of not displaying the HTML when the hidden prop is specified, but the Component doesn’t need to receive the prop when being passed to the Hidable function.

Anything that I change, breaks the other functions. Any idea how to fix this or configure typing properly?

I need this file to stringify a book, a chapter, and a verse but it stringifies multiple books at once

This file splits the text variable from book, chapter, and verses. It should ideally look like this:

[
  {
    "book": "PLACEHOLDER",
    "chapters": [
      {
        "chapter": 1,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 1, chapter 1, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 1, chapter 1, verse 2"
          }
        ]
      },
      {
        "chapter": 1,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 1, chapter 2, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 1, chapter 2, verse 2"
          }
        ]
      }
    ]
  },
  {
    "book": "PLACEHOLDER",
    "chapters": [
      {
        "chapter": 1,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 2, chapter 1, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 2, chapter 1, verse 2"
          }
        ]
      },
      {
        "chapter": 2,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 2, chapter 2, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 2, chapter 2, verse 2"
          }
        ]
      }
    ]
  }
]

Instead, I got this, which duplicated the book but moved on to the next chapter:

[
  {
    "book": "PLACEHOLDER",
    "chapters": [
      {
        "chapter": 1,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 1, chapter 1, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 1, chapter 1, verse 2"
          }
        ]
      },
      {
        "chapter": 1,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 1, chapter 1, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 1, chapter 1, verse 2"
          }
        ]
      }
    ]
  },
  {
    "book": "PLACEHOLDER",
    "chapters": [
      {
        "chapter": 2,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 1, chapter 2, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 1, chapter 2, verse 2"
          }
        ]
      },
      {
        "chapter": 2,
        "verses": [
          {
            "verse": 1,
            "text": "this is book 1, chapter 2, verse 1"
          },
          {
            "verse": 2,
            "text": "this is book 1, chapter 2, verse 2"
          }
        ]
      }
    ]
  }
]
let text = `
this is book 1, chapter 1, verse 1.
this is book 1, chapter 1, verse 2.
*
this is book 1, chapter 2, verse 1.
this is book 1, chapter 2, verse 2.
#
this is book 2, chapter 1, verse 1.
this is book 2, chapter 1, verse 2.
*
this is book 2, chapter 2, verse 1.
this is book 2, chapter 2, verse 2.
`;

let volume = [];
let book = text.split("#");

book.forEach((bookText) => {
    let chapter = bookText.split("*");
    chapter.forEach((chapterText, chapterIndex) => {
        let verse = chapterText.split(".");

        volume.push({
            book: "PLACEHOLDER",
            chapters: chapter
                .filter((chapter) => chapter.trim() !== "")
                .map(() => ({
                    chapter: chapterIndex + 1,
                    verses: verse
                        .filter((verse) => verse.trim() !== "")
                        .map((verse, verseIndex) => ({
                            verse: verseIndex + 1,
                            text: verse.trim() + "",
                        })),
                })),
        });
    });
});

console.log(JSON.stringify(volume, null, 2));

Is there a possibility that it is the double map method and or the double forEach method? I tried removing either of them but would give me errors like (bookText.split is not a method and chapterText.split is not a method.)

is web development still exists after AI revolution , I have 2 years whats technologies and languages i am focus on [closed]

In the dynamic realm of technology, the trajectory of web development intersects with the transformative force of artificial intelligence (AI), ushering in a new era of innovation and possibility. As the boundaries of what’s achievable in web development expand with the proliferation of AI, developers are presented with both challenges and opportunities. In navigating this landscape, the question arises: What avenues should developers explore to remain at the forefront of web development in the wake of AI’s evolution?

Firstly, a foundational understanding of AI principles is indispensable. Developers must familiarize themselves with machine learning algorithms, neural networks, natural language processing (NLP), and other AI technologies that underpin modern web applications. By grasping these concepts, developers gain the insight needed to integrate AI-driven functionalities seamlessly into their projects.

One avenue for leveraging AI in web development lies in the realm of data-driven decision-making. Developers skilled in data analysis and interpretation can harness AI algorithms to glean actionable insights from vast datasets, enabling them to tailor user experiences, optimize content delivery, and drive business growth.

Moreover, the synergy between AI and human creativity presents boundless opportunities for innovation. Developers adept at crafting AI-powered experiences that resonate with users on a deeply personalized level stand to revolutionize the way we interact with the web. Whether through recommendation engines, predictive analytics, or intelligent chatbots, AI empowers developers to create immersive, tailored experiences that captivate and engage users.

However, the rise of AI also brings forth concerns surrounding cybersecurity and data privacy. Developers must prioritize the implementation of robust security measures to safeguard sensitive user information from potential threats and breaches. Additionally, a thorough understanding of regulatory frameworks such as GDPR is essential to ensure compliance and uphold ethical standards in the handling of user data.

Furthermore, as AI continues to permeate various facets of web development, developers must remain agile and adaptable. Keeping abreast of emerging trends such as Progressive Web Apps (PWAs), voice user interfaces (VUIs), and augmented reality (AR) enables developers to stay ahead of the curve and pioneer innovative solutions that push the boundaries of what’s possible on the web.

In essence, the evolution of AI presents both challenges and opportunities for web developers. By embracing AI as a catalyst for innovation and continuously expanding their skill set to encompass AI-driven technologies, developers can chart a course towards success in the ever-evolving landscape of web development.

Novice Developer Looking for API

I’m a novice developer and I am trying to create a fake website for practice. I was advised to use an API in order to make it responsive. (I am a teacher and I am making the site specifically to teach my material to students).

Can anyone recommend a good book, tutorial video, or website that can explain how to choose and set up an API with my code? (So far, my code is just some CSS, HTML, & Javascript, but I hope to add more).

Again, I am a novice, so please be as detailed as possible.

Thank you for your time!

p.s. I’m not sure if it makes a difference or not, but I have a Mac.

Socket.io not receiving request

I have three HTML files, JS attached, and also the Server

Home, this just allows the client to either create a room or join through a UUID.

<!DOCTYPE html>
<html>
<head>
    <title>Kahoot Clone</title>
</head>
<body>
    <h1>Kahoot Clone</h1>
    <button id="createRoom">Create Room</button>
    <input type="text" id="roomId" placeholder="Room ID">
    <button id="joinRoom">Join Room</button>
    <script src="/socket.io/socket.io.js"></script>
    <script src="script.js"></script> 
</body>
</html>
const socket = io();

document.getElementById('createRoom').addEventListener('click', () => {
    socket.emit('createRoom');
    window.location.href = 'teacher.html';
});

document.getElementById('joinRoom').addEventListener('click', () => {
    const roomId = document.getElementById('roomId').value;
    socket.emit('joinRoom', roomId);
    window.location.href = 'student.html';
});

Student

<!DOCTYPE html>
<html>
<head>
    <title>Student's Room</title>
</head>
<body>
    <h1>Starting Soon...</h1>
    <script src="/socket.io/socket.io.js"></script>
    <script>const socket = io();</script> 
</body>
</html>

Teacher screen, which should log if a student has joined the session through the UUID generated in the console, this is the file I cannot seem to get any information in

<!DOCTYPE html>
<html>
<head>
    <title>Teacher's Room</title>
</head>
<body>
    <h1>Teacher's Room</h1>
    <p>Your Room ID: <span id="roomIdDisplay"></span></p> 
    <div id="joinedStudents"></div>
    <script src="/socket.io/socket.io.js"></script>
    <script src="teacher.js"></script> 
</body>
</html>
const socket = io();
const joinedStudents = document.getElementById('joinedStudents');
const roomIdDisplay = document.getElementById('roomIdDisplay');


socket.on('roomId', (roomId) => {
    console.log('Received roomId:', roomId); 
    roomIdDisplay.textContent = roomId; 
});


socket.on('studentJoined', (message) => {
    joinedStudents.textContent = message;
});

And my Server javascript file that is using Express and Sockets.io as the back-end

const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const { v4: uuidv4 } = require('uuid'); // For generating room IDs


const path = require('path'); 

// Serve static HTML files
app.use(express.static(path.join(__dirname, 'public'))); 

// Handle Socket.IO connections
io.on('connection', (socket) => {
    // ... (Inside the io.on('connection'... block)
    socket.on('createRoom', () => {
        console.log('Teacher created a room')
        const roomId = uuidv4(); // Generate a unique ID
        console.log(roomId);
        socket.join(roomId);
        socket.emit('roomId', roomId); // Send ID back to the teacher client
    });
    socket.on('joinRoom', (roomId) => {
        console.log('Student joined room:', roomId);
        socket.join(roomId);
        io.to('teacherRoom').emit('studentJoined', 'A student has joined');
    });
});

http.listen(3000, () => {
    console.log('Server listening on port 3000');
});

For some reason, the teacher script is not firing back to me the roomId, and if a student has joined, I don’t understand why it’s not connecting when I’ve looked at the documentation and done it appropriately.

How to request a cross-origin file that contains relative URLs?

I have a situation where I have two servers, Server A and Server B. (Both are running on localhost on different ports.)

Server A:

a/
  index.html
  index.js

Server B:

b/
  library.js
  font.ttf

Server B hosts an library.js and font.ttf. To load this font file, the library.js file has a fetch call with a relative path, like so:

fetch('./font.tff')

When loaded from it’s own origin, the Server B setup works fine.

However, when loaded a cross-origin request from Server A (with a/index.js importing b/library.js), Server B‘s code fails because now that relative './font.ttf' path is relative to Server A instead (on a different port), which has no such file.

Is there a way to continue to use relative paths on Server B, while having code be isolated so that it can be requested from a different origin and still work?


(The nuances of why I have two servers running has to do with Electron, and how Server A is the renderer process itself, and Server B is my own extra server with a dynamic set of files that might get loaded.)

500 Server Error Posting Payment to Stripe

I am trying to build a learning eCommerce project with NextJS, Sanity, and Stripe. Almost the entire project is done, but I cannot seem to get the checkout to work appropriately. I get this error:

XML Parsing Error: no root element found
Location: http://localhost:3000/api/stripe
Line Number 1, Column 1

This is using a react component from @stripe/react-stripe-js which I’ve not seen in other projects (they usually use a portal instead).

User puts in card info (in this case stripe testing numbers), presses checkout and this logic fires:

const Cart = () => { 

const cart = useCartStore(state => state.cart); 
const removeFromCart = useCartStore(state => state.removeFromCart); 
const totalItems = useCartStore(state => state.totalItems); 
const cartTotal = useCartStore(state => state.cartTotal);

const handleRemoveFromCart = (productId) => { removeFromCart(productId) }

const stripe = useStripe(); const elements = useElements();

const onSubmit = async () => {

const cardElement = elements?.getElement("card");
console.log(cardElement);

try{
  console.log('try is firing')
  if (!stripe || !cardElement) return null;

  const data = await axios.post("api/stripe", {
    amount:cartTotal
  })

  console.log(data)
  const res = await stripe?.confirmCardPayment(data?.data?.intent, {
    payment_method:{
      card:cardElement
    }
  })

  const status = res?.paymentIntent?.status;
  
  console.log(status);

} catch (error) {
  console.log(error)
}

}

I can see the console.log statements just fine, so the function is working in that regard, but I just get a “no root element” error.

The client should send to the endpoint on my server file, and that should submit the information to stripe.

Here is the endpoint:

import { NextResponse } from "next/server"; import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

export async function POST(req) { console.log(stripe); const {data} = await req.json(); const {amount} = data; console.log(amount);

try { const payIntent = await stripe.paymentIntents.create({ amount:Number(amount) * 100, current: "USD" })

return NextResponse.json({status:200, intent:payIntent?.client_secret})

} catch(error) { return NextResponse.json({status:400}) } }

The API endpoint sits in api/stripe/route.js in the Next 14 app router. The call uses axios.

For some reason the 500 error does not show up in the network tab of my browser, and this seems like it maybe some sort of CORS error or blocking happening by stripe, but I really do not know. I’ve tried fixing env variables and sanity schemas, but the error still persist. I’ll be playing with postman and the dashboard in stripe now.

Here’s the github itself:
https://github.com/BDunnCode/nextjsecommerce4

It is based on this tutorial which is quite recent:
https://www.youtube.com/watch?v=hySzY3Xt0_0&t=11251s&ab_channel=CodingWithDouglas

How do I set new text in space on the left and right of a centered div?

webpage
index.html

Changed to left from center, moved all centered image to the left. Typed in text, started underneath the Title. Looked in CSS, could make no determination how to establish area for separate text entry.Went online and searched for solutions, as I have done here. I took a web design beginner course in Coursera, passed the 3 week course in 6 days, but she specified that it was only html5 code, with CSS, and this seems to be a styling issue. I am going to take a course with Codecademy that includes both html5 and CSS.

Cannot read properties of undefined (reading ‘settings’) in Firebase authentication

I’m trying to make a register page using Firebase authentication, but it keeps throwing the same error every time. This is my code:

      <form id="form">
        <div class="sign-in">
            <input class="signin-input" type="text" id="username" name="username" placeholder="Username">
            <input class="signin-input" type="email" id="email" name="email" placeholder="Email">
            <input class="signin-input" type="password" id="password" name="password" placeholder="Password">

            <div id="button_container">
                <input type="submit" id="signUp" name="signup_submit" value="Register">
            </div>
        </div>
    </form>
    <script type="module">
      // Import the functions you need from the SDKs you need
      import { initializeApp } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-app.js";
      import { getDatabase } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-database.js";
      import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-auth.js";

      // Your web app's Firebase configuration
      const firebaseConfig = {
        // Firebase Configuration
      };

      // Initialize Firebase
      const app = initializeApp(firebaseConfig);
      const database = getDatabase(app);
      const auth = getAuth();
      
      signUp.addEventListener('click',(e) => {
        
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;
        var username = document.getElementById('username').value;
        
        createUserWithEmailAndPassword(email, password)
          .then((userCredential) => {
          const user = userCredential.user;
          alert('Successfully registered!');
        })
          .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          
          alert(errorMessage);
        });
      });
    </script>

Every time I press the Register button, it throws me this error: “Cannot read properties of undefined (reading ‘settings’)”