Ask how to resolve persistent high memory usage when reading files from ArrayBuffer in web application

You’ve written logic to convert a file to an ArrayBuffer and process it when the user selects it via a file picker. Initially, you tried to do this using the FileReader API, but you ran into an issue where the memory usage kept increasing and didn’t decrease over time. You changed your code to use Blob.prototype.arrayBuffer() as an alternative, but this still didn’t solve the memory usage issue.

I implemented it using the code below.

async function pickAndReadFileAsArrayBuffer() {
  try {
    // openFilePicker를 호출하여 파일 선택기를 엽니다.
    const [fileHandle] = await window.showOpenFilePicker();
 
    // 선택된 파일을 가져옵니다.
    const file = await fileHandle.getFile();
 
    // FileReader를 사용하여 파일을 ArrayBuffer로 읽습니다.
    const reader = new FileReader();
 
    reader.onload = (e) => {
      const arrayBuffer = e.target.result;
      // ArrayBuffer 처리 로직, 예를 들어 콘솔에 출력
      console.log(arrayBuffer);
 
      // 처리가 완료되면, 이벤트 핸들러를 해제하여 FileReader 객체에 대한 참조를 제거합니다.
      reader.onload = null;
      reader.onerror = null;
    };
 
    reader.onerror = (e) => {
      console.error('File reading failed', e);
 
      // 오류가 발생한 경우에도 이벤트 핸들러를 해제합니다.
      reader.onload = null;
      reader.onerror = null;
    };
 
    reader.readAsArrayBuffer(file);
  } catch (err) {
    // 사용자가 파일 선택을 취소하거나 오류가 발생한 경우
    console.error(err.name, err.message);
  }
}
 
// 함수 호출하여 파일 선택과 ArrayBuffer로의 읽기 과정을 실행
pickAndReadFileAsArrayBuffer();

async function pickAndReadFileInChunks() {
  try {
    // 파일 선택기를 엽니다.
    const [fileHandle] = await window.showOpenFilePicker();
    const file = await fileHandle.getFile();

    const chunkSize = 1024 * 1024; // 1MB
    let startPosition = 0;

    while (startPosition < file.size) {
      const endPosition = startPosition + chunkSize;
      const chunk = file.slice(startPosition, endPosition);
      const arrayBuffer = await chunk.arrayBuffer();
      // 여기서 각 chunk의 ArrayBuffer를 처리합니다.
      console.log(arrayBuffer);
    clearInterval(arrayBuffer)

      startPosition += chunkSize;
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

// 함수 호출하여 파일 선택과 분할 읽기 과정을 실행
pickAndReadFileInChunks();

Require() and import don’t seem to work the same way [duplicate]

For webdev context I want my index.js to import index.json.

When I make use of require() I receive the JSON on my VSCode debug console, but on my browser I get the error ReferenceError: require is not defined

try {
    const dataJson = require('./index.json');
    console.log(dataJson[0]);
} catch(e) {
    console.log(e);
}

But when I use import, I receive the JSON on my browser, but my VSCode console returns an exception Uncaught SyntaxError: Cannot use import statement outside a module

import jsonImport from './index.json' assert {type: 'json'};
console.log(jsonImport[0]);

Can I get some leads on how to properly import JSON to my .js files?

React component input re-rendering or resetting to the default value

I have this component called in the parent component:

{idEdit === comment._id && (
                            <InputComment
                                className={"comment-form-edit"}
                                onClick={sendEdit}
                                cancel={cancelEdit}
                                defaultValue={comment.comentario}
                                comentarioId={comment._id}
                                setFiles={setFiles}
                                files={files}
                                inputRef={inputRef}
                                // commentValue={commentValue}
                                // onChange={onChangeInputComment}
                            />
                        )}

In this component, the user can type a comment or send files. However, when clicking on handleFile or handleRemoveFile, the value typed in the Comment input resets to the default value. As can be seen in the props passed by the parent component, I also tried setting a state on the Comment input value and onChange. It works, but every time I type a character, the input loses focus due to the re-rendering. Here’s the component:

const InputComment = ({
    className,
    onClick,
    cancel,
    defaultValue,
    comentarioId,
    setFiles,
    files,
    inputRef,
    commentValue,
    onChange
}) => {

    const handleFile = useCallback(
        (e, commentId) => {
            const newFiles = Array.from(e.target.files);
            setFiles((prevFiles) => ({
                ...prevFiles,
                [commentId]: [...(prevFiles[commentId] || []), ...newFiles],
            }));
        },
        [setFiles]
    );

    const handleRemoveFile = useCallback(
        (index) => {
            setFiles((prevFiles) => ({
                ...prevFiles, 
                [comentarioId]: prevFiles[comentarioId].filter((_, i) => i !== index),
            }));
        },
        [comentarioId, setFiles]
    );
    return (
        <>
            <div>
                <Comment
                    className={className}
                    ref={inputRef}
                    placeholder="Type a comment..."
                    // defaultValue={defaultValue}
                    // value={commentValue}
                    // onChange={(e)=>{onChange(e.target.value)}}
                    // value={comment}
                    // onChange={(e) => {
                    //  handleChangeComment(e);
                    // }}
                    onChange={()=> {console.log(inputRef.current.value)}}
                />
                <Button
                    component="label"
                    variant="outlined"
                    startIcon={<AttachFileIcon />}
                    style={{
                        marginTop: "-40px",
                        marginLeft: "8px",
                    }}
                >
                    Send file
                    <VisuallyHiddenInput
                        type="file"
                        onChange={(e) => {
                            handleFile(e, comentarioId);
                        }}
                        multiple
                    />
                </Button>
            </div>
            <div style={{ display: "flex", gap: "1em" }}>
                <Buttons variant="contained" onClick={() => onClick()}>
                    Send
                </Buttons>
                <Buttons variant="contained" onClick={() => cancel()} style={buttonCancel}>
                    Cancel
                </Buttons>
                {files && files[comentarioId] && files[comentarioId].length > 0 ? (
                    files[comentarioId].map((file, index) => {
                        return (
                            <div style={{ display: "flex" }} key={index}>
                                <p>{file.name}</p>
                                <IconButton
                                    aria-label="remove"
                                    style={{ color: "red" }}
                                    onClick={() => {
                                        handleRemoveFile(index);
                                    }}
                                >
                                    <HighlightOffIcon />
                                </IconButton>
                            </div>
                        );
                    })
                ) : null}
            </div>
        </>
    );
};

export default InputComment;

ToDo APP Border color change depending on priority

I been wondering if there is any way to add a color depending on the selected priority into a ToDo List Card/Activity created.

I been trying to make this change into a ToDo APP that was created in freeCodeCamp JS, the name of it is “Learn Local Storage by building a ToDo APP”.

Anything helps.

I tried doing several things but, what I was mainly trying to do is getting the card’s/activity or whatever is in the toDo list change its border color depending on it’s priority.

I get the error “Unsupported Media Type Did not attempt to load JSON data(…).”

I am using python and flask, and I am trying to make a web application for making flashcards. However, when I try to submit my flashcards (i.e., when I fill out the fields “course”, “lecture”, “front” and “back”, and press “Enter”), I get the error “Unsupported Media Type Did not attempt to load JSON data because the request Content-Type was not ‘application/json’.”. To my understanding, I am executing my JSON properly, but there seems to be a mistake somewhere. Can anyone help me or give recommendations? Any help is appreciated. This is my app.py.

from flask import Flask, request, render_template, redirect, flash, jsonify, make_response
import sqlite3
import random

app = Flask(__name__)

# Set a secret key for the session cookie
app.secret_key = "secret"

# Connect to the database
conn = sqlite3.connect("flashcards.db")

db = conn.cursor()

# Create a table to store the flashcards
db.execute("CREATE TABLE IF NOT EXISTS flashcards (id INTEGER PRIMARY KEY, user TEXT, course TEXT, lecture INTEGER, front TEXT, back TEXT)")
conn.commit()

@app.route("/", methods=["GET", "POST"])
def make():
    if request.method == "GET":
        user = request.cookies.get("user")

        if user:
            # Get the courses and lectures from the database using the db variable
            db.execute("SELECT DISTINCT course FROM flashcards WHERE user = ?", (user,))
            courses = db.fetchall()
            db.execute("SELECT DISTINCT lecture FROM flashcards WHERE user = ?", (user,))
            lectures = db.fetchall()
            # Pass the courses and lectures to the render_template function
            return render_template("make.html", courses=courses, lectures=lectures)
        else:
            # If there are no cookies, generate a random user name
            user = "user" + str(random.randint(1000, 9999))
            # Pass the user name to the render_template function
            return render_template("make.html", user=user)

    elif request.method == "POST":
        # Get the JSON data from the request
        data = request.get_json()
        # Get the user, course, lecture, front, and back values
        user = data["user"]
        course = data["course"]
        lecture = data["lecture"]
        front = data["front"]
        back = data["back"]
        # Check if the course already exists in the database, and if not, create a new one using the db variable
        db.execute("INSERT INTO courses (name) SELECT ? WHERE NOT EXISTS (SELECT 1 FROM courses WHERE name = ?)", (course, course))
        conn.commit()
        # Check if the lecture already exists in the database, and if not, create a new one using the db variable
        db.execute("INSERT INTO lectures (course, number) SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM lectures WHERE course = ? AND number = ?)", (course, lecture, course, lecture))
        conn.commit()
        # Add the flashcard using the db variable
        db.execute("INSERT INTO flashcards (user, course, lecture, front, back) VALUES (?, ?, ?, ?, ?)", (user, course, lecture, front, back))
        conn.commit()
        # Create a response object
        response = make_response(jsonify({"success": True}))
        # Set a cookie with the user value
        response.set_cookie("user", user)
        # Return the response object
        return response

And this is my “make.html”

{% extends "layout.html" %}

{% block title %}
    Make
{% endblock %}

{% block main %}
<h1>Make Flashcards</h1>
<div class="container">
  <div class="row">
    <div class="col-md-6">
      <form id="flashcard-form" method="POST" action="/">
        <div class="form-group">
          <label for="course">Course</label>
          <input type="text" class="form-control" id="course" name="course" placeholder="Enter the course name" list="courselist" required>
          <datalist id="courselist">
            {% for course in courses %}
            <option value="{{ course }}">{{ course }}</option>
            {% endfor %}
          </datalist>
        </div>
        <div class="form-group">
          <label for="lecture">Lecture</label>
          <input type="number" class="form-control" id="lecture" name="lecture" placeholder="Enter the lecture number" list="lecturelist" required>
          <datalist id="lecturelist">
            {% for lecture in lectures %}
            <option value="{{ lecture }}">{{ lecture }}</option>
            {% endfor %}
          </datalist>
        </div>
        <div class="form-group">
          <label for="front">Front</label>
          <input type="text" class="form-control" id="front" name="front" placeholder="Enter the question or term" required>
        </div>
        <div class="form-group">
          <label for="back">Back</label>
          <input type="text" class="form-control" id="back" name="back" placeholder="Enter the answer or definition" required>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </div>
</div>
{% endblock %}

<script>
  // Adding an event listener to the form which triggers when the user presses the enter key
  document.getElementById("flashcard-form").addEventListener("keydown", function(event) {
    // Checking if the key being pressed is "Enter"
    if (event.keyCode === 13) {
      // Preventing the default form submission
      event.preventDefault();
      // Getting the front and back input values
      var front = document.getElementById("front").value;
      var back = document.getElementById("back").value;
      // Creating a data object to send to the server
      var data = {front: front, back: back};
      // Using fetch to send the data to the server
      fetch("/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
      .then(function(response) {
        // Handling the response from the server
        return response.json();
      })
      .then(function(data) {
        // If the data was successfully sent, show a message and clear the fields
        if (data.success) {
          alert("Flashcard created successfully!");
          document.getElementById("front").value = "";
          document.getElementById("back").value = "";
        } else {
          // If the submission failed, show an error message
          alert("Flashcard creation failed!");
        }
      })
      .catch(function(error) {
        // Handle any errors
        console.error(error);
      });
    }
  });
</script>

I tried checking my imports, and they seem all fine. I also tried asking Copilot and ChatGPT, but they also say that my code looks fine. For some reason, I seem to have issues when using the debugger of VScode.

Detect ScrollTop() for options

I’m working on loading options using ajax

I need to detect scrollTop when scrolling the options to call ajax to load more data

I’ve searched a lot about scrollTop() for options but I’ve found that the options doesn’t support detecting scrollTop();

how to fix please

her is my code :

<html>
<head>
    <title>Webslesson Tutorial | Auto Load More Data on Page Scroll with Jquery & PHP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <select id="load_data"></select>
    </div>
</body>
</html>
<script>
    $(document).ready(function() {
        var limit = 50;
        var start = 0;
        var action = 'inactive';
        function load_country_data(limit, start) {
            $.ajax({
                url: "fetch.php",
                method: "POST",
                data: {
                    limit: limit,
                    start: start
                },
                cache: false,
                success: function(data) {
                    $('#load_data').append(data);
                    if (data == '') {
                        $('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
                        action = 'active';
                    } else {
                        $('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
                        action = "inactive";
                    }
                }
            });
        }
        if (action == 'inactive') {
            action = 'active';
            load_country_data(limit, start);
        }
        $(window).scroll(function() {

            console.log($('#load_data').scrollTop());
            console.log($('#load_data').height());

            if ($(window).scrollTop() + $('#load_data').height() > $("#load_data").height() && action == 'inactive') {
                action = 'active';
                start = start + limit;
                setTimeout(function() {
                    load_country_data(limit, start);
                }, 1000);
            }
        });
    });
</script>

and here is the code of fetch.php:

<?php
if (isset($_POST["limit"], $_POST["start"])) {
    for ($i = $_POST["start"]; $i < $_POST["start"] + $_POST["limit"]; $i++) {
        echo '<option>item ' . $i . '</option>';
    }
}

text not starting to fill up from the designated square

I have the following code which I’m using to move the blue color text boxes to the grid. There’s a reOrder array that drives how the text boxes are filled up. So H1 to H6 will be filled up first and then G1 to G6 etc as you can see when you click on the Move Text Content! button. The limit1 variable and limit2 variables have values 85 and 91 respectively.

/*

Requires jquery + UI

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js

*/

$(".words").draggable({
  revert: function (event, ui) {
    var bRevertingPhrase = this.closest("#drop-em");

    if (!bRevertingPhrase.length) {
      var phraseID = $(this).data("id");
      var phraseHomeID = $(this).parent().data("id");

      //If the child and parent ids don't match, we move the child to the correct parent
      if (phraseID !== phraseHomeID) {
        var correctCell = $("#phrase").find("div[data-id='" + phraseID + "']");
        correctCell.prepend(this);
      }
    }
    return !event;
  }
});
$("#drop-em > div").droppable({
  drop: function (ev, ui) {
    $(ui.draggable)
      .detach()
      .css({ top: 0, left: 0 })
      .appendTo($(this).find(".content:empty"));
    $("#move-text").addClass("disabled");
  }
});
$("#phrase > div").droppable({
  drop: function (ev, ui) {
    $(ui.draggable).detach().css({ top: 0, left: 0 }).prependTo(this);
  }
});

const myButton = document.querySelector("#move-text");
myButton.addEventListener(
  "click",
  () => {
    fill();
  },
  {
    once: true
  }
);

var reOrder = [];
function fill() {
  const cells = document.querySelectorAll("#phrase > div > span");
  var newLoc = "";

  myButton.classList.add("disabled");

  cells.forEach((cell, index) => {
    newLoc = document.querySelector(
      ".item:nth-child(" + reOrder[index] + ") .content "
    );
    newLoc.append(cell);
    newLoc.classList.add("moved");
  });
}
function reArrange() {
  var limit1 = 85;
  var limit2 = 91;

  for (let loop = 0; loop < 8; loop++) {
    for (let i = 0; i < 6; i++) {
      reOrder.push(limit1 + i);
    }
    limit1 = limit1 - 12;
  }
  for (let loop = 0; loop < 8; loop++) {
    for (let j = 0; j < 6; j++) {
      reOrder.push(limit2 + j);
    }
    limit2 = limit2 - 12;
  }
  console.log("reOrder array");
  console.log(reOrder);
}
reArrange();
html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  counter-reset: columnCount 1 alphaCount cellCount;
}
h1 {
  text-align: center;
}
.wrap {
  display: flex;
  gap: 2rem;
  position:relative;
  padding-left:220px;
}

.grid {
  margin: auto;
  display: grid;
  flex: 1 0 0;
  grid-template-columns: repeat(12, 1fr);
  padding-top: 1.5rem;
}

.item {
  position: relative;
  background-color: #f9f9f9;
  border: 1px solid grey;
  aspect-ratio: 1/1;
  counter-increment: columnCount;
  min-width: 0;
  transition: background 1s ease;
}
.item:nth-of-type(12n + 1) {
  counter-increment: alphaCount;
}
.item:nth-of-type(12n + 1)::before {
  content: counter(alphaCount, upper-alpha);
  position: absolute;
  display: flex;
  align-items: center;
  top: 0;
  bottom: 0;
  left: -1.75rem;
  color: red;
  pointer-events: none;
}
.item:nth-of-type(n + 13)::after {
  display: none;
}
.item::after {
  content: counter(columnCount);
  position: absolute;
  left: 0;
  right: 0;
  text-align: center;
  top: -1.75rem;
  color: red;
  pointer-events: none;
}
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow: auto;
  color: #000;
  padding: 1rem;
  word-wrap: break-word;
  counter-increment: cellCount;
}

.words {
  cursor: move;
  transition: padding 0.5s ease;
}
.content:has(.ui-draggable-dragging) {
  overflow: visible;
}
.ui-droppable-active .content {
  overflow: visible;
}
.words.ui-draggable-dragging {
  background: blue;
  padding: 5px 10px;
  border-radius: 6px;
  z-index: 999;
  color: #fff;
  display: block;
  width: 50px;
  height: 50px;
  overflow: hidden;
}
#phrase {
  position:absolute;
  left:0;
  top:0;
  bottom:0;
  color: #fff;
  width:150px;
  overflow:auto;
  z-index: 2;
  display: flex;
  flex-direction: column;
  margin:1rem 0 .5rem;
}
#phrase > div {
  margin: 0 0 10px;
  width:150px;
  padding: 5px 10px;
  background: #007bff;
  border: 2px solid #007bff;
  border-radius: 6px;
  color: #fff;
}
#phrase > div:empty {
  background: #fff;
  border-style: dashed;
  padding: 0px 25px;
  min-height: 30px;
}

.moved {
  animation: fade 3s ease;
}
@keyframes fade {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
    background: red;
  }
}

.item .content::before {
  content: counter(cellCount);
  position: absolute;
  top: 2px;
  left: 2px;
  font-size: smaller;
  color: #666;
  border-radius: 50%;
  border: 1px solid red;
  background: white;
  width: 1.2rem;
  height: 1, 2rem;
  display: grid;
  place-items: center;
}

#move-text.disabled{
  cursor:none;
  pointer-events:none;
  opacity:0.5;
}
#phrase:has(.ui-droppable-active){
  overflow:visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- You'd need to set up something different for touch devices though -->
<h1>Drag and drop example </h1>
<button id="move-text" type="button">Move Text Content!</button>
<div class="wrap">
  <div id="phrase">
    <!-- remove whitespace from  inside div html and then we can use :empty in css to change background -->
    <div data-id="1"><span data-id="1" class="words">H1 Text</span></div>
    <div data-id="2"><span data-id="2" class="words">H2 Text</span></div>
    <div data-id="3"><span data-id="3" class="words">H3 Text</span></div>
    <div data-id="4"><span data-id="4" class="words">H4 Text</span></div>
    <div data-id="5"><span data-id="5" class="words">H5 Text</span></div>
    <div data-id="6"><span data-id="6" class="words">H6 Text</span></div>
    <div data-id="7"><span data-id="7" class="words">G1 Text</span></div>
    <div data-id="8"><span data-id="8" class="words">G2 Text</span></div>
    <div data-id="9"><span data-id="9" class="words">G3 Text</span></div>
    <div data-id="10"><span data-id="10" class="words">G4 Text</span></div>
    <div data-id="11"><span data-id="11" class="words">G5 Text</span></div>
    <div data-id="12"><span data-id="12" class="words">G6 Text</span></div>
  </div>

  <div id="drop-em" class="grid">
    <div class="item">
      <div class="content"></div><!-- must have no spaces inside .content -->
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    <div class="item">
      <div class="content"></div>
    </div>
    

  </div>
</div>

Based on the logic I’ve from the following code, I can figure out what cell value belongs to different cells. Let’s say I want to find out what the cell number for cell A4 is, so the following code gives me 46. If I plug in 46 in the above code’s reArrange function for the limit1 variable, I was expecting the text to start filling up from cell A4 but it doesn’t work as expected. Any idea what’s wrong I’m doing in the reArrange function of above code?

const myRow = document.querySelector("#inp1");
const myCol = document.querySelector("#inp2");
const myButton = document.querySelector("#calculate");
const myAnswer = document.querySelector("#cellnum");
myButton.addEventListener("click", () => {
  var rowNumber = myRow.value.toUpperCase();
  var colNumber = myCol.value;
  var result = 0;
  switch (rowNumber) {
    case "A":
      rowNumber = 42;
      break;
    case "B":
      rowNumber = 36;
      break;
    case "C":
      rowNumber = 30;
      break;
    case "D":
      rowNumber = 24;
      break;
    case "E":
      rowNumber = 18;
      break;
    case "F":
      rowNumber = 12;
      break;
    case "G":
      rowNumber = 6;
      break;
    case "H":
      rowNumber = 0;
      break;
  }

  if (colNumber < 7) {
    result = rowNumber + parseInt(colNumber);
  } else {
    result = rowNumber + 42 + parseInt(colNumber);
  }
  
  console.log("Value of result");
  console.log(result);
  
  myAnswer.innerHTML = result;
});
input,
button,
label {
  display: block;
  margin: 0 0 0.5rem;
}
<label for="inp1">Enter a row A - H</label>
<input id="inp1" placeholder="Enter Row">
<label for="inp2">Enter a column 1 - 12</label>
<input id="inp2" placeholder="Enter Column">
<button id="calculate">Calculate</button>
<p>The cell number is <b id="cellnum">?</b>

what other Font Awesome icons are there? [closed]

I just learned about Font Awesome icons

and i’m interested in learning and finding more to use.Anyone knows any other or all the icons to use dealing with Font Awesome icons please help and thank you.

I was just trying to add a different button or bulletin and learned about this new icon (well new to me).

Creating a truck check system in PHP [closed]

Im in the process of creating a web application for fire departments. One of the features is the “Truck Check” page. If each truck was the same, it’d have the same checklist, but all the trucks are different. Im having trouble creating this entire feature. This is how it should be laid out:

“Truck Check Page —> List of all departments apparatus —> Click on one and that check pops up —>
They can view/complete/and edit the check.”

My problem is that I need to be able to have each department add their own apparatus’s and then insert their own checks. For each truck check, it needs to be organized:

“In cab —> Check 1, Check 2, etc. ; Compartment 1 —> Check 1, Check 2, etc ; and so on”

I dont know how to do this without hard coding.

I understand that this is vague. I just need some tips, or at least a good starting point. I appreciate all of you!

What is the SIMPLEST way to send file input via AJAX & PHPMailer? [duplicate]

I’m trying to send a file input on my form via AJAX and PHPMailer however, readying absolutely everything online and trying examples I’m not sure what the best method is.. Surely this can be done in a few lines of code? I can’t find a good enough guide / demo anywhere online or on the stackoverflow site to go through

Would be GREAT if someone could show a way for multiple file uploads from one input field too?

File input:

<input type="file" name="attachments" id="attachments"/>

JS Formdata:

attachments : $('#attachments').prop('files')

AJAX Post:

$.ajax({ type: "POST", url: 'sendmail.php', data: form_data, async: true, success: function(value) { }, error: function(value) { } });

PHP Side?

$attachments = $_FILES['attachments'];

How to use javascript localstorage to add pokemon to favorites

I am pretty new with localstorage
, JS in general, but my question is how can i favorite my pokemon by using localstorage. Basically a toggle function if it’s already registerd as added to favorites, it’ll unfavorite if you’ll press on the button again. I have the code i need, but it doesn’t favorite the pokemon.

So here’s the thing i tried. First of all i managed to get fix it (with the help of ChatGPT). But the problem is that i can’t use it’s code, because i haven’t learnt that specific code ChatGPT gave me, and i want to do this on my own. THis is their code:

window.addEventListener('load', init);
let name;
let tags;
let favorite;

function init() {
    if (typeof window.localStorage === "undefined") {
        console.error('Local storage is not available in your browser');
        return;
    }
}
document.addEventListener('DOMContentLoaded', function () {
    const containers = document.querySelectorAll('.container');

    // Check localStorage for favorites data
    const favorites = JSON.parse(localStorage.getItem('favorites')) || {};

    // Function to update favorite status
    function updateFavoriteStatus(id) {
        if (favorites[id]) {
            containers[id - 1].classList.add('favorite');
        } else {
            containers[id - 1].classList.remove('favorite');
        }
    }

    //  click event to each "Add to Favorites" button
    document.querySelectorAll('.add-to-favorites').forEach((button, index) => {
        button.addEventListener('click', function () {
            const containerId = index + 1;

            // Toggle favorite status
            favorites[containerId] = !favorites[containerId];

            // Save to localStorage
            localStorage.setItem('favorites', JSON.stringify(favorites));

            // Update favorite status
            updateFavoriteStatus(containerId);
        });

        // Initial update of favorite status
        updateFavoriteStatus(index + 1);
    });
});

So, this works. I reworked the code on my own, but here lies the problem. So whenever i tried running it, i couldn’t see all of my containers. Second of all when i checked for any errors i got this: TypeError: favorite is not iterable
at getPokemonSuccesHandler (task.js:87:30). So i scoured the internet and the problem was that it expected an array. So i found out i could use if (!Array.isArray(favorite)) { favorite = []; }
. I saw my containers, but the button still didn’t work. How can i fix the problem? It’d also be cool when a pokemon has been favorited, the container of the pokemon would get a different color. Here’s my reworked code:

window.addEventListener('load', init)
let name;
let tags;
let favorite = JSON.parse(localStorage.getItem("favorites")) || [];
let apiurl = 'http://localhost/prg03-eindopdracht/webservice/index.php';
let gallery;
let pokedata = {};
function init() {
let gallery = document.getElementById('gallery');
gallery.addEventListener('click', pokemonClickHandler)
    ajaxRequest(apiurl, getPokemonSuccesHandler)
    let title = document.getElementById('title');
gallery.appendChild(title);

}

// document.addEventListener('DOMContentLoaded', function () {
//     const containers = document.querySelectorAll('.container');
//
//     // Check localStorage for favorites data
//     const favorites = JSON.parse(localStorage.getItem('favorites')) || {};
//
//     // Function to update favorite status
//     function updateFavoriteStatus(id) {
//         if (favorites[id]) {
//             containers[id - 1].classList.add('favorite');
//         } else {
//             containers[id - 1].classList.remove('favorite');
//         }
//     }
//
//     //  click event to each "Add to Favorites" button
//     document.querySelectorAll('.add-to-favorites').forEach((button, index) => {
//         button.addEventListener('click', function () {
//             const containerId = index + 1;
//
//             // Toggle favorite status
//             favorites[containerId] = !favorites[containerId];
//
//             // Save to localStorage
//             localStorage.setItem('favorites', JSON.stringify(favorites));
//
//             // Update favorite status
//             updateFavoriteStatus(containerId);
//         });
//
//         // Initial update of favorite status
//         updateFavoriteStatus(index + 1);
//     });
// });
function ajaxRequest(url, successCallback) {
    fetch(url)
        .then((response) => {
            if (!response.ok) {
                throw new Error(response.statusText);
            }
            return response.json();
        })
        .then(successCallback)
        .catch(ajaxRequestErrorHandler);
}


/**
 *
 * @param data
 */
function getPokemonSuccesHandler (data) {
    console.log('a')
    let gallery = document.getElementById('gallery');
    if (!Array.isArray(favorite)) {
        favorite = [];
    }

    for (let mons of data) {
        let pokemonContainer = document.createElement('div');
        pokemonContainer.classList.add('container');

        let title = document.createElement('div');
        title.classList.add('food-name');
        title.innerHTML = `${mons.name} (#${mons.id})`;
        pokemonContainer.appendChild(title);
        let buttonContainer = document.createElement('div');
        buttonContainer.classList.add('button-container');

        let addToFavoritesButton = document.createElement('button');
        addToFavoritesButton.classList.add('button', 'add-to-favorites');
        addToFavoritesButton.innerHTML = 'Add to Favorites';
        addToFavoritesButton.dataset.id = mons.id;
        // replace class add-to-favirte with added
        for (let checkFav of favorite) {
            if (checkFav === mons.id) {
                addToFavoritesButton.classList.replace("favorites", "added")

            }

        }
        buttonContainer.appendChild(addToFavoritesButton);

        let showInfoButton = document.createElement('button');
        showInfoButton.classList.add('button', 'show-info');
        showInfoButton.innerHTML = 'Show Info';
        buttonContainer.appendChild(showInfoButton);

        pokemonContainer.appendChild(buttonContainer);
        let image = document.createElement('img');
        image.src = mons.img;
        console.log(image)
        pokemonContainer.appendChild(image)

        // append containers to the gallery
        gallery.appendChild(pokemonContainer);
        pokedata[mons.id] = mons;
    }


}

/**
 *
 * @param e
 */
function pokemonClickHandler (e) {
    let clickedItem = e.target;
    let globmons = pokedata[clickedItem.dataset.id];

    if (clickedItem.nodeName !== `BUTTON`) {
        return;
    }
    if (clickedItem.classList.contains('favorites')){
        addFavorites(clickedItem)
        console.log("Toegevoegd als fav!")

    }
    else if (clickedItem.classList.contains('added')){
        removeFavorites(clickedItem)
        console.log("ah")
    }

}
function addFavorites(game){
    game.classList.replace("favorites", "added")
    favorite.push(game.dataset.id);
    localStorage.setItem("favorites", JSON.stringify(favorite));

}
function removeFavorites(game){
    game.classList.replace("added", "favorites");
    let index = favorite.indexOf(game.dataset.id);
    favorite.splice(index, 1);
    localStorage.setItem("favorites", JSON.stringify(favorite));

}
function ajaxRequestErrorHandler (data) {
    console.log(data)
}
// window.addEventListener('load', fetchData);


Swiper – Ionic -Angular: When scrolling from last slide and then to the first one index is not reseting

Im using swiper to create a sliding array of number when user can scroll to select his weight. Swiper has [loop]="true" My problem is that once user has reached the limit in my case slider 7 and move to slider 1 the index does not restart to index 0 also if i scroll backwards from slide 1 to 7 i do not have the index updated in my case equal to 6. To have the correct index is very important bacause based on it i update the selected value.

How can I achieve the following goal/intention?

Here is my actual code :

Here is my component.html

<ion-row>
    <ion-col size="10">
      <swiper-container
        #slides
        [options]="sliderOptionsOpts"
        [modules]="swiperModules"
        (swiperslidechange)="checkRangeSlide($event)"
        [loop]="true"
        style="height: 200px"
      >
        <swiper-slide *ngFor="let option of sliderOptions">
          <span
            [ngClass]="option === sliderSelected ? 'fw-bold' : 'text-muted'"
            class="fs-1"
            >{{ option }}</span
          >
        </swiper-slide>
      </swiper-container>
    </ion-col>

Here is my component.ts

sliderOptions: number[] = [];
  sliderOptionsOpts: any;
  sliderSelected: number = 1;

  checkMinMaxRange(max: number, min: number) {
    console.log("max min", max, min);
    const dataArray = this.createArrayFromRange(1, 7);
    this.sliderOptions = dataArray;
    this.sliderOptionsOpts = {
      slidesPerView: 1,
      centeredSlides: true,
      reverseDirection: true,
      initialSlide: this.sliderOptions.indexOf(this.sliderSelected),
      loop: true,
    };
  }

  createArrayFromRange(min: number, max: number): number[] {
    const length = max - min + 1;
    return Array.from({ length }, (_, index) => index + min);
  }

  checkRangeSlide(event: any) {
    let activeIndex = event.detail[0].realIndex;
    const selectedValue = this.sliderOptions[activeIndex];
    const answerObject = {
      selectedValue: selectedValue + 1,
      activeIndex: activeIndex,
      object: event.detail[0],
    };
    console.log("ANSWER:", answerObject);
  }

Is there a way to “hide” a sprite/button so it doesn’t work at certain times?

I am working on a school project. It is a dress-up game where the user dresses up “Lucy” in three outfits. Everything works great until the dates (actual dates “Lucy” is going on).

The dates are just pictures I found on Pinterest. After each date, she would need to go back to her room to change again. However, each sprite background is just a layer and I draw layers on top of the previous one every time the user switches to a new screen.

It is really hard to explain, but every time I click on a button, another button at the same place gets clicked too. Although the second button can’t be seen, it still calls that function and works. I used code.org for this project since I couldn’t find any other website to code that has an easy-to-navigate interface.

Here you can see live preview

World.frameRate = 60;

function date1() {
  if (mousePressedOver(startingbutton)) {
    instruction.visible = true;
    instructionbutton.visible = true;
    instructionbutton3.depth = 14;
  }
  
  if (mousePressedOver(instructionbutton)) {
    showLucyRoom();
    instructionbutton.visible = false;
    instructionbutton2.depth = 10;
  }
  
  if (mousePressedOver(schoolbutton))  {
    CropTop.visible = false;
    sweat.visible = false;
    dress.visible = false;
    school.visible = true;
    school.scale = 0.6;
    instructionbutton2.visible = true;
  }
  
  if (mousePressedOver(sweatbutton))  {
    CropTop.visible = false;
    school.visible = false;
    dress.visible = false;
    sweat.visible = true;
    sweat.scale = 1;
    instructionbutton2.visible = true;
  }
  
  if (mousePressedOver(dressbutton))  {
    CropTop.visible = false;
    school.visible = false;
    sweat.visible = false;
    dress.visible = true;
    dress.scale = 1;
    instructionbutton2.visible = true;
  }
  
  if (mousePressedOver(instructionbutton2)) {
    showCafe();
  }
  
  if (mousePressedOver(instructionbutton3)) {
    showLucyRoom();
  }
}

function date2() {
  if (mousePressedOver(startingbutton)) {
    instruction.visible = true;
    instructionbutton.visible = true;
    instructionbutton3.depth = 10;
    instructionbutton4.visible = false;
  }
  
  if (mousePressedOver(instructionbutton)) {
    showLucyRoom();
    stalker.visible = true;
    stalker.depth = 6;
    instructionbutton4.visible = false;
    instructionbutton4.depth = 10;
  }
  
  if (mousePressedOver(schoolbutton))  {
    CropTop.visible = false;
    sweat.visible = false;
    dress.visible = false;
    school.visible = true;
    school.scale = 0.6;
    instructionbutton4.visible = true;
    instructionbutton4.visible = false;
  }
  
  if (mousePressedOver(sweatbutton))  {
    CropTop.visible = false;
    school.visible = false;
    dress.visible = false;
    sweat.visible = true;
    sweat.scale = 1;
    instructionbutton4.visible = true;
    instructionbutton4.visible = false;
  }
  
  if (mousePressedOver(dressbutton))  {
    CropTop.visible = false;
    school.visible = false;
    sweat.visible = false;
    dress.visible = true;
    dress.scale = 1;
    instructionbutton4.visible = true;
    instructionbutton4.visible = false;
  }
  
  if (mousePressedOver(instructionbutton4)) {
    showMuseum();
  }
  
  if (mousePressedOver(instructionbutton3)) {
    showLucyRoom();
  }
}

function showLucyRoom() {
  LucyRoom.visible = true;
  CropTop.visible = true;
  CropTop.scale = 0.6;
  schoolbutton.visible = true;
  schoolbutton.scale = 0.4;
  sweatbutton.visible = true;
  sweatbutton.scale = 0.4;
  dressbutton.visible = true;
  dressbutton.scale = 0.4;
  cafe.visible = false;
  museum.visible = false;
  instructionbutton3.visible = false;
  instructionbutton3.depth = 14;
}

function showCafe() {
  cafe.visible = true;
  cafe.scale = 2.3;
  text("This was super fun, I’d love to go with you again!", 28, 26);
  instructionbutton3.visible = true;
  instructionbutton3.depth = 14; // Ensure instructionbutton3 is on top
}

function showMuseum() {
  museum.visible = true;
  museum.scale = 2.3;
  text("This is the second date of the day!", 28, 26);
  instructionbutton3.visible = true;
  instructionbutton3.depth = 14; // Ensure instructionbutton3 is on top
}

var background = createSprite(200, 200);
background.setAnimation("StartingPage");

var startingbutton = createSprite(104, 228);
startingbutton.setAnimation("StartingPageButton");

var instruction = createSprite(200, 200);
instruction.visible = false;
instruction.setAnimation("InstructionPage");

var instructionbutton = createSprite(88, 372);
instructionbutton.visible = false;
instructionbutton.setAnimation("InstructionPageButton");

var instructionbutton2 = createSprite(240, 320);
instructionbutton2.visible = false;
instructionbutton2.setAnimation("InstructionPageButton");

var instructionbutton3 = createSprite(328, 354);
instructionbutton3.visible = false;
instructionbutton3.setAnimation("InstructionPageButton");

var instructionbutton4 = createSprite(238, 268);
instructionbutton4.visible = false;
instructionbutton4.setAnimation("InstructionPageButton");

var LucyRoom = createSprite(200, 200);
LucyRoom.visible = false;
LucyRoom.setAnimation("Lucy'sRoom.jpg");

var CropTop = createSprite(72, 220);
CropTop.visible = false;
CropTop.setAnimation("CropTop");

var school = createSprite(72, 215);
school.visible = false;
school.setAnimation("School");

var schoolbutton = createSprite(218, 138);
schoolbutton.visible = false;
schoolbutton.setAnimation("SchoolButton");

var dress = createSprite(100, 215);
dress.visible = false;
dress.setAnimation("dress");

var sweat = createSprite(72, 215);
sweat.visible = false;
sweat.setAnimation("sweatshirt");

var sweatbutton = createSprite(340, 138);
sweatbutton.visible = false;
sweatbutton.setAnimation("sweatbutton");

var dressbutton = createSprite(336, 310);
dressbutton.visible = false;
dressbutton.setAnimation("dressbutton");

var cafe = createSprite(200, 200);
cafe.visible = false;
cafe.setAnimation("cafe");

var museum = createSprite(200, 200);
museum.visible = false;
museum.setAnimation("museum");

var stalker = createSprite(117,236);
stalker.visible = false;
stalker.setAnimation("stalker");

function draw() {
  date1();
  date2();
  drawSprites();
}

I’ve tried using .visible, but that only changes whether the user can see it or not. It doesn’t actually stop the button from responding.