“handleClicks is declared but it’s value is never read” being shown as an error when I have a button set to it on click

I’m trying my best to figure out React, and I’m attempting to make a simple counter, but StackBlitz is continually throwing the error in the title. I have a object in my HTML as <button onclick="button">.

First, I tried putting the onclick in the HTML that gets returned, but I can’t get that to work right without the editor yelling at me for code blasphemy, or something. Second, I tried, just in-case it was something that was wrong with clicks += 1 and it not telling me, switching += to =+, and making the clicks variable into countValue, but nothing did anything.
My code in app.tsx is: (and apologies if it sucks, i have next to no idea what im doing)

var clicks = 0

function handleClicks() {
  clicks += 1
  return (<button>
    {clicks}
          </button>
  );
}

My HTML is as follows:

<html>
  <body>
    <button onclick="HandleClicks()" class="button">
      Button
    </button>
  </body>
</html>

and, my main.tsx, which was already there when i started the project:

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

Autoplay with html and js doesn’t work even with muted atribute

I’ve been trying to ad background music to my website for months now, it used to work using an iframe and embed youtube but that doesn’t autoplay anymore.
I’ve been looking up this issue all morning but no solution actually works, at best it requres user interaction to start playing the audio, which is undesired in my case.

All solutions boiled down to muting the audio then making it play with javascript like below.

<audio controls autoplay muted>
    <source src ="audio.mp3">
</audio>

<script>
  var audio = document.querySelector("audio");
  audio.muted = true;
  audio.play(); 
  audio.muted = false;
</script>

I tried many variations of this, like not trying to play with javascript, only unmuting

<audio controls autoplay muted>
    <source src ="audio.mp3">
</audio>

<script>
  audio.muted = false;
</script>

But the audio doesn’t even play by itself. Is there no solution to this problem?

Vue.js application(global build) is not working

I’m learning vue.js, everything worked fine but today vue decided that it won’t work for no reason.
Vue devtool extension doesn’t detect my code, dynamic content is not working and console throws error: Vue is not defined. I tried to solve this problem with some solutions that i found e.g.:
var Vue = require('vue'), import Vue from 'vue' nothing worked.

Here is whole code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue podstawy</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
    <nav class="navbar navbar-lg navbar-light bg-light">
        <div class="container-fluid">
            <a href="#" class="navbar-brand">My Vue</a>
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li v-for="link in links" class="nav-item">
                    <a href="" class="nav-link" aria-current="page">{{link.text}}</a>
                </li>
                
            </ul>
        </div>
    </nav>
    <div id="content" class="container">
        <h1>{{ pageTitle }}</h1>
        <p>{{ content }}</p>
    </div>
    <script>
        Vue.createApp({
            data(){
                return{
                    links:[
                    {text:'Home',url:'home.html'},
                    {text:'About',url:'home.html'},
                    {text:'Contact',url:'home.html'}
                ]
                }
            }
        }).mount('nav');
        Vue.createApp({
            data(){
                return {
                    pageTitle: 'Hello Vue',
                    content: 'Welcome to wonderful world of Vue'
                };
            }
        }).mount('#content');

    </script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>
</html>

I didn’t change any line of code and followed every step from a tutorial. Where is the problem?

How to make an HTML form be permanent after filling out the field, but before submitting?

Context: I think that filling out a form in a paper with a pen brings the person to pay more attention to what it writes and I wonder if there is a way to bring that to a html form.

Expected Behaviour: The person clicks on a checkbox and it stays like that unless the person reloads the page, it cannot be “unclicked”, or a person writes a settence in a text field and, after it presses enter (or tab) the field can’t be edited.

Doesn’t have to behave exactly like that, any suggestion close to it will be helpful. It can be in HTML, Js, Python (for Django) or whatever, just wondered if there is a “simple” way or it would be a separate project all throughout.

Tried searching on google but didn’t find anything close to that.

comments logged on console after onContextMenu trigger function in my react application appears for a split second and disappears

I’ve been facing this issue since a long time and can’t get over it. I have a react application and I’ve set up onContextMenu which calls a function handleTableRightClick when triggered. Inside the function I’ve set up logs and other tasks to ececute. but when I see on my console of brave browser, the logs in the handleTableRightClick function appears for a split second and disappeares.

Here is my onContextMenu trigger (they are present for each row):

  <tr
   key={i}
   onContextMenu={(e) => handleTableRightClick(e, o, i)}
   >

Here is my handleTableRightCLick function:

 const handleTableRightClick = (e, rowData, i) => {
    e.stopPropagation();
    e.preventDefault();
    const contextMenuWidth = 200;

    const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
    const scrollY = window.pageYOffset || document.documentElement.scrollTop;
    const xMultiplier = e.clientX > window.innerWidth / 1.5 ? -1 : 0;
    setMenuPosition({
      x: e.clientX + scrollX + contextMenuWidth * xMultiplier,
      y: e.clientY + scrollY,
    });

    setIsRightClickMenuOpen(true); // Open the right-click menu

    
  };

I’ve looked over default behaviour and propagation and added them but its still not working.

Grouping items in a list based on attribute values inside a mustache template

Say I had a list of ‘bookings’:

[
  {
    Date: { S: '2024-04-10' },
    BookingID: { N: '3' },
    Room: { S: 'Pod1' }
  },
  {
    Date: { S: '2024-04-10' },
    BookingID: { N: '5' },
    Room: { S: 'Pod2' }
  },
  {
    Date: { S: '2024-05-13' },
    BookingID: { N: '2' },
    Room: { S: 'Pod3' }
  }
]

How would I format my mustache file to group bookings together depending on their date for example?

Would I have to use a script? I can display the list on my mustache file using:

{{#bookings}}
  <p>Date: {{date}}
  <p>ID: {{id}}
  <p>Room: {{room}}
{{/bookings}}

But I’m not sure where I’d even start to be able to group them together by date.

Apologies if this wasn’t worded the best, I’m still getting used to writing decent questions here! TIA

How to handle multiple async functions when fetching for emails and attachments with IMAP and javascript

I am using IMAP library and javascript to fetch for emails.

My plan is the following:

  1. Fetch for the emails by email, subject, and a time range.
  2. Look for the emails number.
  3. For each email, I need to look for the attachments that contains PDF files.
  4. And for each attachment, i need to build an object, push it inside an array and send it to frontend only if the function ended. It doesn’t matter if I send an empty array

The problems i encounter now
For now, I sent to the specific email two emails that contains each same pdf, and same subject.

  1. Instead of receiving two objects inside the array, sometime I receive one, sometime I receive empty array… But never two objects like I need…

What I tried

  1. Defined the imap search function and before, initialised an empty array where I need to send the object after finished fetching.
  2. Created a stream from the fetch function defined in the point above. The fetch took a message param, again as a stream.
  3. Executed simple parser function and for each parsed document that have attachments, created an objects that will be sent to frontend.

The code

fetch.on('message', (msg) => {

                    msg.on('body', (stream) => {
                        simpleParser(stream, async (err, parsed) => {
                            if (err) throw err;
                            if (parsed.attachments) {
                                //defined already as an empty array    
                                attachmentPromises = parsed.attachments.map(async (attachment, index) => {
                                    return new Promise((resolve, reject) => {
                                        if (attachment.contentType === 'application/pdf') {
                                            // Process the pdf here...
                                            resolve({
                                                object details with key value pairs. 
                                            });
                                        }
                                         
                                        else {
                                            resolve(null); 
                                        }
                                    });
                                });
                                
                                //We wait for the promises to resolve
                                Promise.all(attachmentPromises).then(attachments => {
                                    //we get only the values that are not null
                                    const validAttachments = attachments.filter(attachment => attachment !== null);
                                    allAttachmentsData = allAttachmentsData.concat(validAttachments);
                                });

                            }
                        });
                    });
                    
                });

The fetch events

   fetch.once('error', (err) => {
                    console.log('Fetch error: ' + err);
                });


                fetch.once('end', function () {
                    //allAttachmentsData is empty 
                    return res.status(200).json(allAttachmentsData);
                })

NodeJS/Electron ‘IF’ statement not working with numerical inputs

I’m struggling to figure out why my ‘if includes’ statement is not working within the code below. I have used the same method throughout my project to filter the data from other files which has been working fine. The only difference here (other than var names and the file it’s pulling from) is that the user input is a numerical substring and not text. Does it behave differently with numbers?

I have tried replacing ‘serialmodel’ within the if statement with the ‘serial’ var instead and adding a line to my CSV containing the full serial number, still no output. If I try .includes(‘19180’) it still does not work however if I replace it with ‘testing’ and add the line ‘testing’ to the CSV it does work.

function FilterModels() {
    const fs = require("fs");
    const { parse } = require("csv-parse");

    var serial = document.getElementById("serialnumberinput").value;
    var serialmodel = serial.substring(0,5); //Adding .value to this results in 'undefined'
    var logger = document.getElementById("filtermodeltest");

    logger.innerHTML += serialmodel; // Outputs "19180"

    fs.createReadStream("./model-test.csv")
        .pipe(parse({
            delimiter: ",",
            from_line: 1,
        }))

    .on("data", function(row) {
        console.log(row);
        logger.innerHTML += row; // Outputs "19180-Black", "19180-Green" and all other lines from the CSV

        if (row.includes(serialmodel)) {
            logger.innerHTML += row; //Doesn't output anything
        }

        else {

        }
    })
}

SweetAlert2 CSP (style-src-elem) rror

I’ve got website that uses Sweetalert2 script.
CSP header is:
“style-src-elem ‘self’ fonts.googleapis.com *.jsdelivr.net”

Browser is sending me error:
Refused to apply inline style because it violates the following Content Security Policy directive: “style-src-elem ‘self’ fonts.googleapis.com *.jsdelivr.net”.

I’m using nonce for implementing sweetalert script.

Is there any other solution except adding unsafe-inline in CSP?

To be even more precize browser added errors in this lines of code
screenshoot from console

i’ve tried to add in CSP that CDN domain “*.jsdelivr.net”

Update object property after form submission for use in a seperate function

How to update a specific proprety listed in an object?

I tried so many variations that I am not sure the code makes sense any more.

let object= {
    proprety1:'',
    ...

}

Whether these propreties are populated, a different .div will be displayed:

   document.addEventListener("DOMContentLoaded", function(){
        if(object.proprety1 === ""){
            document.querySelector('.first-screen-div').style.display = 'flex';
            form.addEventListener('submit', function(event) {
                newObjectForm(event);
            });
        }else {
            document.querySelector('.second-screen-div').style.display = 'flex';
        }

        
    })

The form is handled in the below function:

let form = document.getElementById('object-form');
form.addEventListener('submit', newObjectForm);
function newObjectForm(event){
    event.preventDefault();
    let objectOne = document.getElementById('object-one').value;

    object.proprety1= objectOne 

    document.getElementById('object-form').submit();

}  

I want this empty proprty to be updated after submission of a form, with the form value so I can reuse it with future functions.

here is the form:

<div class="first-screen-div">
            <form method="GET" action="" class="" id="object-form">
       
                <input type="text" id="object-one" name="object-one" placeholder="" class="" required><br><br> 
 
                <button class="" type="submit">Submit</button>
            </form>
</div>

If I console.log() outside the function, the value entered in the form is not printed, which makes me thing the data is updating Proprety1.

I also used .push() which didnt result in better result. I am clearly doing something wrong but cannot find the root cause.

Any suggestion?

Hugo + Javascript unable to access html

I am a newbie to Hugo and am currently just playing around with a basic template to get a feeling for it. As i’m trying to integrate a javascript snippet to build a popup it seems like the script is unable to call or change my html and css.

`console.log('Am here?');

const popup = document.getElementsByClassName('tryme')[0];
function openPopup(){
popup.style.display = 'block';
console.log('Hello?');
}

function hello(){
for (let i = 0; i < 50; i++) {
    console.log(i);
      }
}  
hello()

console.log('Hello?');` 


`<!DOCTYPE html>
<html lang="{{ or site.Language.LanguageCode site.Language.Lang }}" dir="{{ or 
site.Language.LanguageDirection `ltr` }}">
<head>
{{ partial "head.html" . }}
</head>
<body id="body">
<header>
<button onclick="openPopup">OPEN</button>
<div class="tryme"></div>
{{ partial "header.html" . }}
</header>
<main>
{{ block "main" . }}{{ end }}
</main>
<footer>
{{ partial "footer.html" . }}
</footer>

</body>

</html>`


`.tryme {
  position: fixed;
  background-color: antiquewhite;
  width: 100%;
  height: 100%;
   display: none;
}`

I have tried adding the script into the baseof.html or the main.js but got the same results either way. i have also tried to adress the html in different ways (id, class, queryselector), i have also added different print commands at different stages of the script and the ones that don’t refer to any html are working fine, only the one inside the function that is supposed to change the display property of .tryme is not showing in the console.

ReactJS – Errors mapping over dictionary array elements

I have a dictionary made like this:

const dictionary = {
        array: [{
            property1: 'property1',
            property2:[{
                nestProperty1: 'nestProperty1',
                nestProperty2: [
                    'leaf1',
                    'leaf2'
                ]},
                {
                nestProperty1: 'nestProperty2',
                nestProperty2: [
                    'leaf3',
                    'leaf4'
                ]}
            ]
        }]
}

I want to iterate over dictionary[‘array’] which is an Array using the map function.

return ( 
        <div>
            {dictionary["array"].map((element) => (
                <div>Example</div>
            ))}
        </div>
    );

I get three errors:

  1. '{' expected on the closing ‘)’ after element
  2. ',' expected on the =>
  3. Unexpected token on the last }

I’m using the exact same syntax I used in other cases where map worked just fine.

How to use Classes and their getters in Pinia store?

I have defined a Pinia store in which my user’s character is made, stored/retrieved from localStorage, and pushed into an array which the store eventually returns.

This is done by defining the class Character, in which the character’s name, level, and so on is defined.

The problem: some of the values of that class are getters or (computed()=>{...}), which don’t fire after the characters array is imported and stored to refs in a component.

I’ve tried working with both getters and computed values (one of which wraps this in a nested scope, causing problems when referencing other values in the class).

I’ve also migrated all these computed values into a separate function instantiate_characters() that is called whenever the app is loaded, after all characters have been loaded. This works, but I consider it a dirty workaround. I’d much rather just create a new object from a class and have it work dynamically.

Sample:

class Character {
    constructor(existing_character){
        this.general = {
                name: existing_character ? existing_character.general.name : '',
                age: existing_character ? existing_character.general.age : 0,
                // const this_character = this
                // get level(){
                //     let level = 0
                //     for (let c of this_character.general.classes){
                //         level += c.level
                //     }
                //     return level
                // },
                level: computed(()=>{
                    let level = 0
                    for (let c of this.general.classes){
                        level += c.level
                    }
                    return level
                    return this.general.name.length
                }),
                classes: [
                    // an array with classes (e.g. Warrior), 
                    // each of which has its own level
                ]
            }
        }
        this.attributes = {
            // ...
        }
    }
}

Creating a list in JS via selected cheboxes values

I want to store the value of several checkboxes (URLs) in a JS variable, and I want the list to be updated everytime a box is checked or unchecked. However I cannot console.log anything and when I ckeck I have a message “updateSelectedImageURLs (this is my function) is not defined”. Do you have an idea why ?

This is my checkbox :

<input 
    type="checkbox" 
    name="crop_checkbox" 
    value="{{ img_file|img_to_iiif:small }}"
    onchange="updateSelectedImageURLs()">

This is my JS :

var checkboxes = document.querySelectorAll('input[name="crop_checkbox"]');
var selectedImageURLs = [];
// function to update
function updateSelectedImageURLs() {
    // empty list
    selectedImageURLs = [];

    // if check
    checkboxes.forEach(function(checkbox) {
        // Vérifier si la case est cochée
        if (checkbox.checked) {
            // retrieve value
            var imageURL = checkbox.value;

            // add url to the list
            selectedImageURLs.push(imageURL);
            }
        }
    );

    // print url list
    console.log(selectedImageURLs);
}

It is enveloped in an event listener “DOMContentLoaded” with the rest of my script for the page.

Thank you so much if you have an idea ?