Live background mp4 not sized correctly [closed]

everyone! I’m working on a simple portfolio website and would like to use a live wallpaper on my About Me page. Everything functions well overall, but I’ve noticed that when I open the page, a horizontal scrollbar appears, and there’s a gap on the left side and top that doesn’t quite fit the screen. This issue only happens at 2K resolution; at 1920×1080, it displays perfectly. Does anyone have suggestions on how to fix this in my code?

I have tried swapping videos and nothing is helping

Sending uploaded files from Javascript to a c# endpoint

I have this code to append a file to a certain index in the collections sent from javascript to a C# endpoint.

const data = row.querySelector(`td[data-bs-column="Action"]`); 

                                if (data) {
                                    const uploadElement = data.querySelector("input[type='file']");
                                    if (uploadElement && uploadElement.files.length > 0) {
                                        const files = Array.from(uploadElement.files);
                                       // formData.append(`vm.Items[${itemIndex}].Attachment`, file);
                                        if (files && files.length > 0) {
                                            files.forEach((file, index) => { 
                                                formData.append(`Items[${itemIndex}].Attachments`, file);
                                            }); 
                                        }
                                    } 
                                }




//ENDPOINT
 [HttpPost, Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public async Task<IActionResult> JSUpdateEvaluationItems(PerformanceViewerViewModel vm)
    {
        var files = HttpContext.Request.Form.Files; //TEST TO CHECK IF THE FILE IS RECEIVED
        var result = await performanceRepository.UpdateEvaluationItems(vm);
        return Json(result.ToString());
    }

As you can see here, i have added this line of code var files = HttpContext.Request.Form.Files; //TEST TO CHECK IF THE FILE IS RECEIVED to check if the formdata sent to the endpoint has a files. And it has the files received from the client.

Now, on the viewmodel on my endpoint is desiged like this

public class PerformanceViewerViewModel : BaseModel
    { 
        public Credentials? Credentials { get; set; }
        public Credentials? KRAOwner { get; set; }
        public List<Entities.Users.Role>? Roles { get; set; }
        public PerformanceConfiguration? Configuration { get; set; }
        public PerformanceInformation? Information { get; set; } 
        public List<Category>? Categories { get; set; }
        public List<Goal>? Goals { get; set; }
        public List<Item>? Items { get; set; }
        public List<Status>? Statuses { get; set; }
        public List<CycleApprover>? Approvers { get; set; }
        public List<SelectListItem>? StatusItems { get; set; }
        public List<AppraisalItem>? AppraisalItems { get; set; }
        public List<Unit>? Units { get; set; }
        public List<Column>? Columns { get; set; }
    }

The object that is receiving the the attachment is the List<Item>? Items.

But when I check on the Attachments inside the Items, there is no file appended.

The model Item is designed like this

public class Item : BaseModel
    {
        public Guid ParentTempID { get; set; } 
        public int ItemID { get; set; }
        public int GoalID { get; set; }
        public string? ItemName { get; set; }
        public decimal ItemPercentage { get; set; }
        public int UnitID { get; set; }
        public string? UnitName { get; set; }
        public bool Ratio { get; set; }
        public string? Consolidated { get; set; }
        public string? Result { get; set; }
        public decimal ItemWeight { get; set; }
        public bool OverrideWeight { get; set; }
        public int ActiveCommentID { get; set; }
        public List<IFormFile>? Attachments { get; set; }
        public List<CompanyTarget>? CompanyTargets { get; set; }
        public List<string>? Filenames { get; set; }
    }

How do I fix cors access control missing header?

This is my js function:

btn = document.getElementById('submit-button')
    btn.addEventListener("click",submitForm)
    function submitForm(){
        fetch('http://localhost:5000/diagnose', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ symptoms: symptoms, email: loggedInUser.email }),
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (resultDiv) {
                displayResults(data, symptoms);
            }
        })
        .catch((error) => {
            console.error('Error:', error);
            if (resultDiv) {
                resultDiv.innerHTML = '<p style="color: red;">An error occurred while processing your request. Please try again.</p>';
            }
        });
    }

This is my server code. I’ve tried to include what the method I am calling, and my imports and anything that might be relevant.

from flask import Flask, request, jsonify, send_from_directory
import json
import os
import traceback

app = Flask(__name__)
ALLOWED_ORIGIN = os.environ.get('ALLOWED_ORIGIN', 'http://localhost:5500')
# Configure logging
logging.basicConfig(level=logging.DEBUG)

# Path to users.json and history file
history_file_path = os.path.join(os.path.dirname(__file__), 'history.json')
users_file_path = os.path.join(os.path.dirname(__file__), 'users.json')


# Middleware function to handle CORS headers
def add_cors_headers(response):
    # Only allow requests from your frontend domain
    response.headers['Access-Control-Allow-Origin'] = 'http://localhost:5500'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    return response

# Register the after_request handler
@app.after_request
def after_request(response):
    return add_cors_headers(response)

# Handle OPTIONS requests
@app.route('/', defaults={'path': ''}, methods=['OPTIONS'])
@app.route('/<path:path>', methods=['OPTIONS'])
def handle_options(path):
    return '', 204


# Diagnose route
@app.route('/diagnose', methods=['POST'])
def diagnose():
    data = request.json
    symptoms = data.get('symptoms', '')
    email = data.get('email', '')
    diagnosis, recommendation = diagnose_and_recommend(symptoms)

    # save history
    history = read_history()
    history['history'].append({
        "email": email,
        "date": datetime.now().isoformat(),
        "symptoms": symptoms,
        "diagnosis": diagnosis,
        "recommendation": recommendation
    })
    write_history(history)

    return jsonify({
        "diagnosis": diagnosis,
        "recommendation": recommendation
    })



# Static files route
@app.route('/<path:filename>')
def serve_static_files(filename):
    return send_from_directory('../', filename)

if __name__ == '__main__':
    app.run(debug=True)

I have tried to allow the headers as you’ll see in the method labelled middleware but I am unfamiliar with cors. I would like to do away with it completely, but I don’t know how to get a response from my python file. I don’t know if it matters but my app.py is in a backend folder, while the js is in the root folder.

h1 Element isn’t working after adding a element [closed]

Making a social media link page and I was adding a tags to the h1 tags in the html. I added a styles in the CSS so it still kept the original h1 styling in the CSS. At first they all worked well. I don’t know what I did, but now its like my h1 tag doesn’t have the a element CSS styling anymore. It just shows the h1 CSS styles, but not the a and :hover styles. And its only for this element. I have a h2 and h3 and they work completely fine, but h1 is causing me a lot of trouble. Maybe while I was testing the links it got overridden?

Don't know how stack overflow wants me to post so Imma just link my code

imgur

leaflet-src.js:1582 Uncaught (in promise) TypeError: Cannot read properties of undefined

This is a really strange error I am getting when adding Leaflet marker(s) to my Vue.js App.
Below is the code I am using:

<LMarker
    v-for="listing in listings"
        :latlng="[listing.lat, listing.lon]"
>
    <ChildVue />   
</LMarker>

When I remove ChildVue, the code works perfectly.
When I add back in ChildVue, I get the below:

leaflet-src.js:1582 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'lat')

It’s odd because my ChildVue looks like this currently, with no calls to lat:

<template>
    <LPopup>
        <p>Hello world!</p>
    </LPopup>   
</template>

<script>
import { LPopup } from 'vue3-leaflet';
import 'leaflet/dist/leaflet.css';

export default {
  components: {
    LPopup
  },
};
</script>

Why does adding this file lead to this error?
Also, when I put the code of ChildVue.vue into my parent, the code works perfectly fine…

Drag And drop library for Javascript Script

I am relatively new to java script. I wanted to create a project where in I will need to drag and drop to rearrange the order of items. I have no idea how to approach this, I was wondering if there was an library that could help. (I want to do this on JS to learn and understand, for that reason I am not opting for any framework like react or angular)

I haven’t tried anything as such for drag and drop. I just have a list of items rendered on the page

Firefox and Safari Very Slow Repainting Lag on Sticky Scroll Reveal

I rebuilt this sticky scroll effect from this site where scrolling will reveal content underneath (so the top and bottom layers are shown simultaneously) using nextjs & tailwind.

It works smoothly in chrome locally and in production. However, in firefox or safari it seems to be janky, repainting the content slowly on every scroll.

Is there something wrong with the below or that can be optimised for these browsers while maintaining the same effect.

Code Sandbox

export default function Home() {
  const projects = [
    {
      title: "Google Search Engine",
      link: "www.google.com",
    },
    {
      title: "Youtube",
      code: "www.youtube.com",
    },
    {
      title: "Discord Chatbot",
      link: "www.discord.com",
      code: "www.discord.com",
    },
  ];

  return (
    <section className="min-h-[300vh] bg-black text-white text-6xl" id="Works">
      {projects.map((project, index) => (
        <div key={index} className={"px-5"}>
          <div className="h-screen contain-paint bg-black border-t border-neutral-600">
            <div
              className={`h-[300vh] w-full absolute left-0 right-0`}
              style={{ top: `${-100 * index}vh` }}
            >
              <div className="sticky top-0 h-screen flex justify-between flex-col lg:flex-row">
                <div className="flex flex-col justify-center h-1/3 lg:h-full lg:w-1/2">
                  {/* TITLE */}
                  <div className="flex items-center font-bold">
                    {index + 1}. {project.title}
                  </div>
                  {/* LINKS */}
                  <div className="flex flex-col justify-center">
                    <div className="mt-5 mr-5">
                      {project.link && (
                        <a
                          href={project.link}
                          className="text-white underline block"
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          Live Site
                        </a>
                      )}
                      {project.code && (
                        <a
                          href={project.code}
                          className="text-white underline block"
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          Source Code
                        </a>
                      )}
                    </div>
                  </div>
                </div>
                {/* IMAGE */}
                <div className="relative flex justify-center items-center h-2/3 lg:w-1/2 lg:h-full px-5 py-5 lg:py-10">
                  <a
                    href={project.link || project.code}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="relative w-full h-full"
                  >
                    {index + 1}. {project.title} images would go here
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      ))}
    </section>
  );
}

I orginally thought it was the images causing this but removing basically all the code besides the project title’s still has the same effect on firefox/safari.

I’ve also tried removing most cosmetic css (like padding, margins) but to no avail.

Cypress tests are passing when they should fail

I’m writing Cypress tests and running them headless in terminal. The tests are passing even when they should fail.

For example writing this code:

describe('Website Landing', () => {    
    it.only('Should load', async () => {
        cy.visit('http://www.mywebsite.com/');
        cy.get('[data-testid="sign-inx"]');
    })
})

And running this on terminal will end on success:

cypress run

But there is no element with such attribute and value. And if I add other assertions at the end, the test keeps passing

cy.get('[data-testid="sign-inx"]').should('have.length', 1);

I don’t understand how Cypress manages to allow tests to pass and to fail. Could someone help?

There is a problem with loading format models.glb in the project on three.js

I’m importing.The glb model is using three, but the model falls apart into the parts it consists of. How can I fix this?

const models = {
  pizza:  { url: 'models/pizza.glb' },
  dodster:  { url: 'models/dodster.glb' },
  cup:  { url: 'models/cup.glb' },
};

const manager = new THREE.LoadingManager();
manager.onLoad = init; // Запуск после загрузки всех моделей

const gltfLoader = new GLTFLoader(manager);
for (const model of Object.values(models)) {
  gltfLoader.load(model.url, (gltf) => {
    model.gltf = gltf; // Сохраняем загруженную модель в объект
  });
}

I tried to download the model for the game, but it’s falling apart

Hard stuck on trying to get images to flip back if incorrectly matched with each other

Trying to create a simple card matching game.

The idea is if you select two different cards in this game, they will flip back and you gain a turned used. If the two cards are the same they stay flipped over, you gain a turn used as well as a point.

However, I am not sure if my code is reading or understanding if the cards are the same or not.

Here is my code:

// Set global variables
const cards = document.getElementsByClassName('card');
let movesDisplay = document.querySelector('.move-counter');
let toggledCardsArray = [];
let move = 0;
let winCount = 0;
const restart = document.getElementById('restart');

const imagesLinkArray = [
    { id: 1, image: './assets/talisman1.png', newAlt: 'talisman1' },
    { id: 2, image: './assets/talisman2.png', newAlt: 'talisman2' },
    { id: 3, image: './assets/talisman3.png', newAlt: 'talisman3' },
    { id: 4, image: './assets/talisman4.png', newAlt: 'talisman4' },
    { id: 5, image: './assets/talisman5.png', newAlt: 'talisman5' },
    { id: 6, image: './assets/talisman6.png', newAlt: 'talisman6' },
    { id: 7, image: './assets/talisman1.png', newAlt: 'talisman1' },
    { id: 8, image: './assets/talisman2.png', newAlt: 'talisman2' },
    { id: 9, image: './assets/talisman3.png', newAlt: 'talisman3' },
    { id: 10, image: './assets/talisman4.png', newAlt: 'talisman4' },
    { id: 11, image: './assets/talisman5.png', newAlt: 'talisman5' },
    { id: 12, image: './assets/talisman6.png', newAlt: 'talisman6' }
];

// Function to restart the game
const restartGame = () => {
    const toggledCards = document.querySelectorAll('.card.toggled');
    toggledCards.forEach((card) => {
        card.classList.remove('toggled');
    });

    // Shuffle the imagesLinkArray
    imagesLinkArray.sort(() => Math.random() - 0.5);

    // Reset game state
    toggledCardsArray = [];
    move = 0;
    winCount = 0;
    movesDisplay.innerText = `Turn(s): ${move}`;

    // Update card images
    const allImagesSrc = document.querySelectorAll('.card-img');
    allImagesSrc.forEach((el, index) => {
        el.src = imagesLinkArray[index].image;
        el.alt = imagesLinkArray[index].newAlt;
        el.id = imagesLinkArray[index].id;
    });
};

// Add event listener to restart button
restart.addEventListener('click', restartGame);

// Function to handle card clicks
for (let i = 0; i < cards.length; i++) {
    cards[i].addEventListener('click', function () {
        // If the card is already flipped or two cards are already in the array, return
        if (this.classList.contains('toggled') || toggledCardsArray.length === 2) return;

        // Add 'toggled' class and add to toggledCardsArray
        this.classList.add('toggled');
        toggledCardsArray.push(this);

        // Check if two cards are flipped
        if (toggledCardsArray.length === 2) {
            let firstCardSrc = toggledCardsArray[0].querySelector('.card-img')?.src;
            let secondCardSrc = toggledCardsArray[1].querySelector('.card-img')?.src;

            // If cards match
            if (firstCardSrc === secondCardSrc) {
                winCount++;
                toggledCardsArray = []; // Clear the array for the next pair
            } else {
                // If cards do not match, flip them back after a delay
                setTimeout(() => {
                    toggledCardsArray.forEach((card) => {
                        card.classList.remove('toggled');
                    });
                    toggledCardsArray = []; // Reset the array
                }, 500);
            }

            // Increment move count and update display
            move++;
            movesDisplay.innerText = `Turn(s): ${move}`;

            // Check if the player has won
            if (winCount === 6) {
                setTimeout(() => {
                    alert(`Congratulations!!! You won the game in ${move} moves.`);
                }, 300);
            }
        }

I have tried to dive deep into Geek4Geeks, since it was following their game similar game that helped me build yet their code and mine don’t produce the same effect when cards are flipped.

How to get rid of the right duplicate audio (during transfer [with DOM related listening events])?

The Prologue & the ask: I’ve been struggling with this problem for the past day, and now I fear I might be in too deep to see a diff strategy; and politely & humbly ask for a multitude of fresh set of eyes to assist me with this issue please. (together, we are amazing.)
=).

The problem: Alright, so I’m going to attach some CSS, HTML, and JavaScript, after asking my question that I seek assistance with. That question sounds like this:

A.) I have a ‘Would you like to upload an Audio?’ button.

B.) I have a text box area thing (called: “messageBox”) where ppl can write stuff like: “I love what I do.” and press submit.
And when they press submit? it shows up in a new area,
in a container called: “BottomRightContainer”.

C.) So, i have a button called:
“Would you like to upload an Audio” button, that (i referenced earlier and)
has the ability to upload multiple audio files (cool).
when we click it, and add an audio (MP3) file?
it gets added to our “messageBox”. (Cool. this is desired.
When we click play? while this MP3 audio file is in the messagebox? it plays. cool. This is desired behavior. everything’s groovy so far homies).

D.1) Now here’s where our issue shows up,
it shows up with an uploaded audio file.
When we upload an audio file and then: “When we click submit?”
the audio file goes from “messageBox” to
“BottomRightContainer”. cool. this is wanted and desired behavior.
D.2) But, for some reason, there’s 2 of em. (this, is NOT, desired behavior).
D.3) and, of the two, one of em does not work. (This is where I need help, and humbly ask for help, REMOVING THE ONE- THAT DOES NOT WORK (AND KEEPING THE ONE THAT DOES- PLEASE)).
D.3.1) and of the two, I seem to have the magical ability, to keep deleting the one that works. Even when I delete different parts of the code.

Here is my CSS HTML and Javascript, all copy paste friendly for one page:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
/* Fancy MP3 info id like to integrate, found below: */
.inline-audio {
display: inline-block;
vertical-align: middle;
}
/* MP3 Player Styling */
.audio-player {
display: flex;
align-items: center;
gap: 10px;
margin: 10px 0;
padding: 10px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: #333; 
color: #fff; 
}

.audio-player button {
/* MP3 Play Button */
background-color: #007bff;
color: white;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}

.audio-player button:hover {
/* Play Button Hover */
background-color: #0056b3;
}

.audio-player .progress {
/* Progress Bar */
flex: 1;
height: 5px;
background-color: #ddd;
border-radius: 5px;
overflow: hidden;
}

.audio-player .progress-bar {
/* Progress Bar Fill */
height: 100%;
background-color: #007bff;
width: 0;
}

.audio-title {
/* MP3 Title */
flex: 2;
}
.audio-duration {
/* MP3 Duration */
flex: 1;
text-align: right;
}

/* Background info, is the CSS found below */

.toolbar {
display: flex;
justify-content: flex-start;
white-space: normal;
margin-bottom: 10px;
}
.toolbar button,
.toolbar select,
.toolbar input {
margin-right: 5px;
padding: 5px 10px;
background: linear-gradient(225deg, #e6e, #ffeb3b); /*As a Thank You, for looking through my Code, i give you, these lovely colors- that i call: "YeBoyPurple" */
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button {
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
background: linear-gradient(225deg, #e6e, #ffeb3b); 
color: #fff;
font-size: 16px;
}
#messageBox {
width: 97%;
height: 100px;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
resize: none;
margin-bottom: 10px;
background-color: #fff;
opacity: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
justify-content: space-between;
}
</style>
</head>
<body>
<div id="BottomContainer">
<div
id="BottomContainerHoldingImageAndMessage"
style="display: flex; flex-direction: row"
>
<div id="BottomLeftContainer">
<div class="toolbar">
<button data-command="insertAudio">Audio?</button>
</div>
<div contenteditable="true" id="messageBox"></div>
<div
class="flexContainer"
style="display: flex; justify-content: space-between"
>
<div><button id="submitButton">Submit</button></div>
<div id="buttonContainer"></div>
</div>
</div>
</div>
</div>
<div id="BottomRightContainer">
<!-- Messages will appear here- like this one: "This Code was Written By: Scholah on StackOverflow" <3 -->
</div>
<script>
const messageBox = document.getElementById("messageBox");
const submitButton = document.getElementById("submitButton");
const bottomRightContainer = document.getElementById(
"BottomRightContainer",
);
const bottomLeftContainer = document.getElementById(
"BottomLeftContainer",
);
const modeSwitch = document.getElementById("modeSwitch");
let audioFiles = [];

document.querySelectorAll("[data-command]").forEach((button) => {
button.addEventListener("click", () => {
const command = button.getAttribute("data-command");
if (
command === "bold" ||
command === "italic" ||
command === "underline"
) {
document.execCommand(command, false, null);
} else if (command === "insertAudio") {
const input = document.createElement("input");
input.type = "file";
input.accept = "audio/*";
input.multiple = true;
input.onchange = function (event) {
const files = Array.from(event.target.files); // Get the selected audio files
files.forEach((file) => {
const audioPlayer = document.createElement("div");
audioPlayer.className = "audio-player"; // Apply Background MP3 styling
const playButton = document.createElement("button");
playButton.innerHTML = "▶"; // Play button
audioPlayer.appendChild(playButton);
const audio = document.createElement("audio");
audio.src = URL.createObjectURL(file); // Set the audio source to the uploaded file
const progress = document.createElement("div");
progress.className = "progress"; // Progress bar container
const progressBar = document.createElement("div");
progressBar.className = "progress-bar"; // Progress bar fill
progress.appendChild(progressBar);
audioPlayer.appendChild(progress);
const title = document.createElement("span");
title.className = "audio-title"; // Display the MP3 file name
title.textContent = file.name;
audioPlayer.appendChild(title);
const duration = document.createElement("span");
duration.className = "audio-duration"; // Display the audio duration
audio.addEventListener("loadedmetadata", () => {
duration.textContent = formatTime(audio.duration);
});
audioPlayer.appendChild(duration);
audio.addEventListener("timeupdate", () => {
// Update the progress bar as the audio plays
const percentage = (audio.currentTime / audio.duration) * 100;
progressBar.style.width = `${percentage}%`;
});
playButton.addEventListener("click", () => {
// Toggle play/pause functionality
if (audio.paused) {
audio.play();
playButton.innerHTML = "❚❚"; // Change to pause button
} else {
audio.pause();
playButton.innerHTML = "▶"; // Change to play button
}
});
messageBox.appendChild(audioPlayer); // Add custom MP3 player to messageBox 
});
};
input.click();
}
});
});
// Handle the submit button click without reattaching event listeners
submitButton.addEventListener("click", () => {
const messageContent = messageBox.innerHTML;
if (messageContent) {
const messageDiv = document.createElement("div");
messageDiv.innerHTML = `<p>${messageContent}</p>`;
// Move existing audio players from the messageBox
const audioPlayers = messageBox.querySelectorAll(".audio-player");
audioPlayers.forEach((audioPlayer) => {
messageDiv.appendChild(audioPlayer); // Move audio player to messageDiv
});

bottomRightContainer.insertBefore(
messageDiv,
bottomRightContainer.firstChild,
);
bottomRightContainer.style.display = "block";
messageBox.innerHTML = "";
audioFiles = [];
document.execCommand("removeFormat", false, null);
}
});
messageBox.contentEditable = true; 
messageBox.spellcheck = true; 
</script>
</body>
</html>

Conclusion: So i come to StackOverflow, to ask for help.

Here’s what i’ve tried and where im at, but i do not recommend reading this next part, because it might taint your attempt at trying to help me, by implementing in your minds eye, a potential wrong path, cause again, im on the wrong end here. anywho, what:
I’ve tried for roughly a day to get to this area. for a hot minute it would not show up in its proper colors. idk why but it didnt. then when i finally got it to show up. it didnt play. then i kept at it till now i somehow managed to come to an understanding that: ‘the reason it didnt play, is because its connected to the DOM(?), and when it gets transferred over, all the event listeners are NOT getting transferred over(?) so i had to duplicate the event listeners(?) and implement them in(?)
which, makes me think: “in its duplication” it might be duplicating the audio file to show up twice? but somehow, the i think DOM duplication thing also worked(?) cause one of the two work? so, like, now i tried removing the first one(?) but then that removes the duplicate(?)so then i tried hiding the first one(?) but then that hid the duplicate(?) and a part of me is like: “why is this taking a whole day? am i in too deep? am i overthinking this? This shouldnt be taking a whole day and im not gonna go into this for two days without some extra help. thas my motto yo. “you get one day. two days? i come back with StackOverflow reinforcements.” If able to figure out how to help me: “move the audio from one box to the other while keeping how it looks and its style and playing without there being a duplicate” that’d be greatly appreciative and id be thankful. Thank you for the priviledge of your time. If unable to help but read all this anywho, thank you for reading =).

(Extra Note:> i also, very very very polietely ask, the stackoverflow editors, to please stop editing out my slang and linguistic flow. we are all flowers of all different varieties, and to grow our coding/programming field, i politely ask the editors, to stop gatekeeping/removing the flavor of our (and my) verbal flow (regardless of your reasoning- thanks) as i ask my question in how i ask it, and then can properly follow up with people who try to help, in a consistent verbal flow- rather than sound one way and then a whole other way since the editing made me sound more like not me due to your lovely edits <3 please and thank you.)

(Extra Extra Note: comments to help me improve the craft (not my linguistic flow) and ideas on how to better tackle on such ideas- are always welcomed and greatly desired/preferred/ & appreciated! THANK YOU!!)

(Extra Extra Extra Note: Teachers, feel free, taking this as a lesson (especially if we find the solution) and tailoring it your own way =) )

HAVE A GREAT DAY EVERYBODY!!!

How could you show a bootstrap alert on mouseover of a choices field in a django form?

I have a questionnaire based on django form and I need to show a note if a user hovers or clicks on a question before it submits. The django form is loaded in from a custom question and question choices model.

I had some luck with custom question formatting prior by handing django form label and choices a mark_safe str with html formatting of the title and options within. I took it a step further for this and attempted to put in some java script as well. Though it does not show anything on mouseover of the choice. In this case answer.content would be the individual choice underneath the question. Below is my mark_safe code which is only called when there is an explanatory_note for this answer choice, it is called right before handing it to django form typed choice field. I tried having it within the html page, but it would not work as it wouldn’t be connected to an individual choice under a question. I have confirmed that the following str is correctly handed to the django form and used as a choice. It does correctly display answer.content.

mark_safe("<p id="" + str(n) + "">" + answer.content + "</p> n"
          "<script>n"
          "const alert" + str(n) + " = document.getElementById('" + str(n) + "')n"
          "if (alert" + str(n) + ") {n"
          "  alert" + str(n) + ".addEventListener('mouseover', () => {n"
          "    appendAlert('" + answer.explanatory_note.text + "', 'primary')n"
          "  })n"
          "})n"
          "</script>n")

Below you can also see some of the html loading the individual form and the java script which should create the alert.

  <div id="liveAlertPlaceholder"></div>
  <form action="" name='question' id='question' method="POST">
    <div class="card mb-4 mt-4">
      <div class="card-body">
        {% csrf_token %}
        {{ form }}
      </div>
    </div>
    <input class="btn btn-success mb-4" type="submit" value="next" />
  </form>
  <script>
    const alertPlaceholder = document.getElementById('liveAlertPlaceholder')
    const appendAlert = (message, type) => {
      const wrapper = document.createElement('div')
      wrapper.innerHTML = [
        '<div class="alert alert-${type} alert-dismissible" role="alert">',
        '   <div>${message}</div>',
        '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
        '</div>'
      ].join('')

      alertPlaceholder.append(wrapper)
    }
    setTimeout(function() {
        bootstrap.Alert.getOrCreateInstance(document.querySelector(".alert")).close();
    }, 3000)
  </script>

If there is an alternative without javascript and/or bootstrap alerts I would love to hear it. I just need a informational note to pop up when a user hovers over or clicks on a choice.

MudText – on ENTER key, determine contents of selected line then act accordingly

I’m trying to develop a custom notepad editor. Currently I’m using the MudText component of MudBlazor for this.

The behaviour I’m seeking is that when a user hits ENTER on their keyboard, I want to check the contents of the selected line and run some custom logic in the KeyPress event.

  1. If current line contains text then create new line/paragraph as normal.
  2. If current line contains no text then prevent text from being added to the editor and popup a menu at that location instead. Here is some code I was playing with. But could not work it out after that. Any help appreciated.
@code
{
    string sampleText = "wwswswLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}

<MudTextField T="string" Label="Multiline" KeyDownPreventDefault="_preventDefault" Variant="Variant.Text" Text="@sampleText" Lines="50" AutoGrow="true" Immediate="true" OnKeyDown="@HandleKeyDown" />


@code {
    bool _preventDefault;
    protected void HandleKeyDown(KeyboardEventArgs e)
    {
        _preventDefault = e.Key == "Enter" && ...?
    }
}

Find out which children element is visible according to its class using a switch-statement in either jQuery or JS?

I’m trying to target the first children <p> element that is visible within its parent element and I can’t solve it on my own.

This is what I put together, but I have no knowledge on how to accomplish this.

This is the original HTML code without the <p> element:

<div class=".result-content">
   <div class="one">Text for one</div>
   <div class="two">Text for two</div>
   <div class="three">Text for three</div>
</div>

When I generate 1 of the 2 <p> elements on the fly, it looks like this:

<div class=".result-content">
   <p class="available">This is available</p>

   <div class="one">Text for one</div>
   <div class="two">Text for two</div>
   <div class="three">Text for three</div>
</div>

or it could be like this:

<div class=".result-content">
   <p class="not-available">This is NOT available</p>

   <div class="one">Text for one</div>
   <div class="two">Text for two</div>
   <div class="three">Text for three</div>
</div>

I’m using the switch statement because to me it looks organized than the if/if else/else statements.

var isVisible = ":visible";
var target = $('.result-content').children(":first");       
//var target;
switch (target.css('display') == isVisible) { 
    case $('.available'): 
        
        console.log('This is available!');
        break;
    case $('.not-available'): 
        console.log('This is NOT available!');
        break;
    default:
        //console.log('Nothing is available!!');
}

Thanks in advance!

How to fill a color in hand drawn shape or closed path in rough js?

I am using RoughJs ( docs ) for my whiteboard app. I have done programming the work of tools like – pencil button, undo button, redo button, clear canvas button, color picker, But struggling to program the fill color button.

In simple words, I want that after selecting fill color button and a color from color picker

It fills color wherever I left click with the mouse on the canvas that’s all.

CODE

import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import rough from 'roughjs'
const roughGenerator = rough.generator()



const WhiteBoard = ({ canvasRef, ctxRef, elements, setELement, tool, color }) => {
  const [isDrawing, setIsDrawing] = useState(false)

  useEffect(() => {
    const canvas = canvasRef.current
    const ctx = canvas.getContext("2d")
    canvas.height = window.innerHeight / 2
    canvas.width = window.innerWidth * 2
    ctx.strokeStyle = color
    ctx.lineWidth = 2
    ctx.lineCap = "round"
    ctxRef.current = ctx
  }, [])


  useEffect(() => {
    ctxRef.current.strokeStyle = color
  }, [color])

  console.log('in elements', elements);

  useLayoutEffect(() => {
    if (canvasRef) {
    const roughCanvas = rough.canvas(canvasRef.current)

    // removes clock effect with lines
    if (elements.length > 0) {
      ctxRef.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height)
    }

    elements.forEach(element => {

      switch (element.type) {
        case "pencil":
          roughCanvas.curve(element.path, {
            roughness: 0,
            curveStepCount: 20,
            bowing: 0.2,
            strokeWidth: 5,
            disableMultiStroke: true,
            stroke : element.stroke,
          })
          break;
      default:
          break;
      }
    });
  }
  }, [elements])

  const handleMouseDown = (e) => {
    const { offsetX, offsetY } = e.nativeEvent

    switch (tool) {
      case "pencil":
        setELement((prevElement) => [
          ...prevElement,
          {
            type: "pencil",
            offsetX,
            offsetY,
            path: [[offsetX, offsetY]],
            stroke: color
          }
        ])
        break;

      default:
        console.log("error in match down handler");
        break;

    }

    setIsDrawing(true)
  }

  const handleMouseMove = (e) => {
    const { offsetX, offsetY } = e.nativeEvent
    if (isDrawing) {
      switch (tool) {
        case "pencil":
          // exract all paths from last element and add more paths like [200,201] to it

          const { path } = elements[elements.length - 1]  // [[1,2],[12,42]]
          const newPath = [...path, [offsetX, offsetY]]

          // adding more paths in last element of elements
          setELement((prevElement) =>
            prevElement.map((ele, index) => {
              if (index == elements.length - 1) {
                return {
                  ...ele,
                  path: newPath
                }
              } else {
                return ele
              }
            })
          )

          break;
        default:
          console.log("error in move handler match");
          break;
      }
    }
  }

   
  const handleMouseUp = (e) => {
    console.log("up", e);
    setIsDrawing(false)
    console.log("elements", elements);
  }


  return (
    <div
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      className='border border-dark border-3 w-100 h-100 overflow-hidden'
    >
      <canvas
        ref={canvasRef} />
    </div>

  )
}

export default WhiteBoard;

You can see a demo in image.

image