HTML / JS Trying to cycle through font options on website with a switch case but its not functioning

I have 6 different options for fonts and I created a button in HTML to call a function onclick. I click it once adn the change works, but when I click it again it does nothing. Definitely missing something and I can”t figure out what it is.

function changeFont() {
  var font = "Arial";
  var fontNum = 1;

  fontNum++;

  switch (fontNum) {
    case 1:
      font = "Josefin Sans";
      break;
    case 2:
      font = "Montserrat";
      break;
    case 3:
      font = "Lora";
      break;
    case 4:
      font = "Suse";
      break;
    case 5:
      font = "Fenix";
      break;
    case 6:
      font = "Courier Prime";
  }

  document.body.style.fontFamily = font;

  if (fontNum >= 6) {
    fontNum = 0;
  }
}
<input type="button" id="font-toggle" value="Aa" onclick="changeFont()" />

It changes to Montserrat, but nothing after.

Any guidance would be appreciated, thank you.

JS only works after selecting an element through the developer screen

I am using document.querySelector(‘#combo_inptxt’).click() to select a dropdown menu, however JS does not recognize the menu until I open the developer and select an element. The dropdown is visually visible but not by JavaScript. It is odd that only opening developer and selecting an element works, while selecting the page itself will not allow querySelector to work. Any guidance is much appreciated.

I have tried window.focus() and trying to change the tabs on the screen because it is on the second tab within a webpage. I have found that I run across this issue as well with Python Selenium since it cannot find the dropdown.

node.js ejs template with datatables not passing variables to if statements

Good evening all, I have a Node.JS application running ejs templates, and on one of those pages is a datatable that has revealable “child” rows. In those child rows are a couple of buttons, and one opens a model to display a form that is going to be populated from a JSON object in data.form_data.

I have my modal html being pulled in via:

<%- include("../dataView/viewFullformModal") %> 

All of my data is available in the “data” variable. It is rendering data.formType, data.customer_name, data.dateReceived, and others; HOWEVER, I am needing to include another ejs file with the specific layout for the various forms. So I figured the easiest way was either an “if” or a “switch” statement and here is where I am having issues: the “data” variable is accessible to the <% if statement.

My if statement is as follows:

<% if ( data.formType === 'Schedule Consultation Form') { %>
    '<p> yes </p>' +
<% } else { %>
    console.log(data.formType) +
<% } %>

This is returning “undefined”; however right before this I have the following code that is working:

'formType: ' + formType + '</br>' +

This returns: “formType: undefined”

And, before this code i have the following that is NOT working:

<% data.formType %>

This returns: “NaN”

This is one of two problems, but it is the major problem right now.

Here is my main template file being loaded as the body: dataTable.ejs

<div class="card">
    <div class="card-header">Submitted Form Data</div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="customer_data" class="table table-bordered">
                <thead>
                    <tr>
                        <th></th>
                        <th>Date Received</th>
                        <th>Form Type</th>
                        <th>Customer Name</th>
                        <th>Email</th>
                        <th>Form Status</th>
                        <th>Reviewed By</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th></th>
                        <th>Date Received</th>
                        <th>Form Type</th>
                        <th>Customer Name</th>
                        <th>Email</th>
                        <th>Form Status</th>
                        <th>Reviewed By</th>
                    </tr>
                </tfoot>
                <tbody></tbody>
            </table>

        </div>
    </div>
</div>

<script>
    $(document).ready(function(){
        function format ( data ) {
            // `d` is the original data object for the row
            console.log ( data.form_data);
            console.log ( data.formType);
            let formType = data.formType;
            return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
                <%- include("../dataViews/childRowHeader") %>
                <%- include("../dataViews/childRowDetails") %>
                <%- include("../dataViews/childRowFormData") %>
                // include Modals
                <%- include("../dataViews/viewFullFormModal") %>
                <%- include("../dataViews/addNotesModal") %>
                <%- include("../dataViews/markReviewedNotesModal") %>

            '</table>';
        }

        //let dataTable = $('#customer_data').DataTable({
        let dataTable = new DataTable($('#customer_data'), {
            'processing' : true,
            'serverSide' : true,
            'serverMethod' : 'get',
            'ajax' : {
                'url' : '/get_data'
            },
            'aaSorting' : [],
            'columns' : [
                {
                    className: 'dt-control',
                    orderable: false,
                    data: null,
                    defaultContent: ''
                },
                { data : 'dateReceived' },
                { data : 'formType' },
                { data : 'customer_name' },
                { data : 'customer_email' },
                { data : 'form_status' },
                { data : 'reviewed_by' }
            ]
        });

        dataTable.on('click', 'td.dt-control', function (e) {
            let tr = e.target.closest('tr');
            let row = dataTable.row(tr);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
            }
            else {
                // Open this row
                row.child(format(row.data())).show();
            }
        });

    });

</script>
<script src='../../assets/scripts/modalScript.js' type="application/json">  </script>

Here is the included viewFullFormModal.ejs

'<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">'+
    '<div class="modal-dialog modal-dialog modal-xl" role="document">'+
        '<div class="modal-content">'+
            '<div class="modal-header">'+
                '<h5 class="modal-title" id="exampleModalLabel"><strong>' + data.formType + '</strong> submitted by: ' + data.customer_name + ' on ' + data.dateReceived + '</h5>'+
                '<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">'+
                    '<span aria-hidden="true">&times;</span>'+
                '</button>'+
            '</div>'+
            '<div class="modal-body">'+
                'formType: ' + data.formType + '</br>' +
                'formType: ' + formType + '</br>' +

                <% data.formType %> + '</br>' +
                <% if ( data.formType === 'Schedule Consultation Form') { %>
                    '<p> yes </p>' +
                <% } else { %>
                    '<br>' +
                    console.log(data.formType) +
                <% } %>

            '</div>' +
            '<div class="modal-footer">'+
                '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>'+
                '</div>'+
            '</div>'+
        ' </div>'+
    '</div>'+
'</div>'+

I can remove the whole “if” statement and include the following file (scheduleConsultationFormLayout.ejs) and it returns the data correctly:

'<p>' +
    'First Name: ' + data.form_data[4.3] + '</br>' +
    'Last Name: ' + data.form_data[4.6] +
'</p>' +

How to get the absolute path of a file dragged onto an input file in Electron?

I’m developing an application using Electron and encountered an issue when trying to get the absolute path of a file that has been dragged and dropped onto a file input field.

As we know, Electron uses a browser-based interface, which makes it difficult to access the absolute paths of dragged-and-dropped files. So far, I’m able to get the absolute path of files when opening the file dialog using the dialog.showOpenDialog method in the main process, as shown in the example below:

//Process main (main.js):

// Example of how to get the absolute path of a video
ipcMain.handle('select-file', async () => {
    const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
        properties: ['openFile'],
        title: 'Select your video file',
        filters: [
            { name: 'Videos', extensions: ['mp4', 'avi', 'mov', 'mkv'] }
        ]
    });
    return canceled ? null : filePaths[0];
});
//Renderer process (renderer.js):

uploadSection.addEventListener('click', async () => {
    const filePath = await ipcRenderer.invoke('select-file');
    if (filePath) {
        console.log('Selected file:', filePath);
    }

});

This works well to open the file picker, but I would like to achieve something similar when dragging and dropping the file directly onto the input. However, since the absolute path is not directly accessible via the browser’s file input API, I’m having difficulty implementing this in Electron.

Has anyone faced this or found a solution to obtain the absolute path of a file that has been dragged and dropped onto a file input in Electron?

Thanks in advance for your help!

I’ve tried several methods so far, but none seem to fit my case. I’m also wondering if web.utils.PathForFiles from Electron might be the solution, but I haven’t found any implementation examples for my case.

How to compare two arrays at the index and also include null values in the new array output

So I am very new to coding and have run into an issue when it comes to comparing arrays, especially ones that are nested and trying to pull out values that match using their indices into a new array. Say I have two different arrays in the example where one is a nested array:


const array1 = [1,2,3,4,5,6,7,8,9,10]

const array2 = 
[
[1,2,4,6]
[1,3,7,9,10]
[1,2]
[1,6,8,9]
]

I need the nested array to check each value against the original array to see if it matches and if it does then pull that value into a new array at the same index. IF it doesn’t match at that index then I need it to inert a delimiter or blank value of some kind then finish comparing the rest of the values against the two arrays. I also need the new outputted array to be the same length of the original array, so the expected output for the values above would be:

const ouputtedArray = 
[
[1,2,,4,,6,,,,,]
[1,,3,,,,7,,9,10]
[1,2,,,,,,,,,]
[1,,,,,6,,8,9,]
]
I have tried a couple of different approaches and spent hours online looking for the answer with no hope. For example I have tried to compare the two arrays using a for loop:
for(let i = 0; i <=array1.length;i++){
            if( i + array2[0][i] ==  i + array1[i]){
                const match = i + array2[0][i]
                const arrays =[]
                console.log([match])
            }}

//console.log output
['1']
['2']

The end goal of this entire process is to be able to input this data into a spreadsheet, so I need to keep the blanks to represent empty cells within CSV format, so eventually the overall data would be:

const array1 = [1,2,3,4,5,6,7,8,9,10] // These are the headers for the spreadsheet

const ouputtedArray = // these are the data cells
[
[1,2,,4,,6,,,,,]
[1,,3,,,,7,,9,10]
[1,2,,,,,,,,,]
[1,,,,,6,,8,9,]
]  

and the spreadsheet itself would look like this


| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 
| - | - | - | - | - | - | - | - | - | -- |
| 1 | 2 |   | 4 |   | 6 |   |   |   |    |
| 1 |   | 3 |   |   |   | 7 |   | 9 | 10 |
| 1 | 2 |   |   |   |   |   |   |   |    |
| 1 |   |   |   |   | 6 |   | 8 | 9 |    |

I have no idea what to do here and am struggling to find a solution. Any help would be absolutely amazing!

How to get the first and the last poin values in ECHARTS of the visible zone on the screen when it’s initialized and on resize

I’m trying to get back the first and the last value in ECHARTS on a graph like this

where there’s also a zoomable zone

I’ve tryied

<script>
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);

function test(){
    console.log(myChart.getOption());
}
test();
</script>

that gives back the series object after initialization.

So you can get back the first and last coords like this

    first_serie_coords = myChart.getOption().series[0].coords;
    first_element = first_serie_coords[0]
    last_element = first_serie_coords[first_serie_coords.length - 1]
    
    //console.log(chart.getOption());
    console.log(first_element, last_element)

But how to get also the start end the end point when the graph zooming zone it’s resized?

How to improve my JavaScript for my Accordion Menu to open

What am I doing wrong? Any idea how to make this accordion menu work?

I’ve been trying to figure out why my accordion menu for a Frontend Challenge isn’t working. It’s currently throwing the following error:

Uncaught TypeError: Cannot read properties of undefined (reading ‘toggle’) at HTMLButtonElement.<anonymous>

This error is from Google dev tools. My active class is defined in my css file. I’m trying to make it toggle between two classes when my button is active but I haven’t been able to activate it or toggle it at all.

Can someone help me get an idea of what’s going on?

These are snippets of my code.

const acc = document.getElementsByClassName("accordion_btn");
var i;

for (let i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", (event) => {
    this.classList.toggle("active");
    this.classList.toggle("accordion_btn:hover");

    const panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
.accordion_btn {
  width: 100%;
  background-color: hsl(0, 0%, 100%);
  text-align: left;
  border: none;
  outline: none;
  margin: 20px 0;
  transition: 0.4s;
}

.accordion_btn:hover {
  background-color: hsl(276, 51%, 90%);
}

.active {
  background-color: red;
}

.panel {
  font-weight: 400;
  color: hsl(292, 16%, 49%);
  display: none;
  overflow: hidden;
  margin-bottom: 20px;
  text-align: left;
}
<div class="accordion">
  <button class="accordion_btn">
  What is Frontend Mentor, and how will it help me?
  </button>
  <div class="panel">
    <p> Frontend Mentor offers...</p>
  </div>
</div>

<div class="accordion">
  <button class="accordion_btn">
    Is Frontend Mentor free?
  </button>
  <div class="panel">
    <p>Yes, Frontend Mentor...</p>
  </div>
</div>

<div class="accordion">
  <button class="accordion_btn">
    Can I use Frontend Mentor projects in my portfolio?
  </button>
  <div class="panel">
    <p>Yes...</p>
  </div>
</div>

<div class="accordion">
  <button class="accordion_btn">
    How can I get help if I'm stuck on a Frontend Mentor challenge?
  </button>
  <div class="panel">
    <p>The best place to...</p>
  </div>
</div>
</div>

I tried changing my variable declarations with var and const but that probably has nothing to do with it? I also tried adding defer to my script tag in my original HTML file.

TS – Handle `{data, error} | {data, error}[]` and throw if `error` exists

I’m using supabase. In supabase, API response is structured like {data, error}. data is non-null if the request is succeeded and error is non-null if the request is failed.
So If I want to call an api, I have to handle the response like this:

const {data, error} = await getData();

if (error) {
    throw error;
}

// data is non-null (succeeded)

It could be very burdened if the response is an array:

const [{data: d1, error: e1}, {data: d2, error:e2}] = await Promise.all([getData1(), getData2()]);


if (e1 || e2) {
  throw e1 || e2;
}

// d1 and d2 are non-null

So I’ve created an util function to reduce the effort.

import {type PostgrestError} from "@supabase/supabase-js";

interface IResponse<T> {
    data: T;
    error: PostgrestError | null;
}

interface ISuccessResponse<T> extends IResponse<T> {
    data: NonNullable<T>;
    error: null;
}

const isDataResponse = <T>(res: IResponse<T>): res is ISuccessResponse<T> => !res.error;

export const throwIfError = <T>(res: IResponse<T>): ISuccessResponse<T> => {
    if (isDataResponse(res)) {
        return res;
    }

    throw res.error;
};
// very simple!
const {data} = throwIfError(await getData());

// data is non-null!

It works well if the response is not an array. However it cannot handle array response.

const [{data: d1}, {data: d2}] = throwIfError(await Promise.all([getData1(), getData2()]));

I surely know how to write a logic for JS but not TS.

export const throwIfError = res => {
    if (Array.isArray(res)) {
        if (res.every(isDataResponse)) {
            return res;
        }

        throw res.find(r => !isDataResponse(r)).error;
    }

    if (isDataResponse(res)) {
        return res;
    }

    throw res.error;
}

I want throwIfError to handle array response as well. Could you help me?

DOMParser parseFromString() Ignores Certain Tags [duplicate]

First question ever! I’m stumped.

I have a web app which will, upon a user action, send a table row <tr>...</tr> to the browser to replace a row that already exists. It works great, but the <tr> element includes several dataset values that are used in Javascript, and when the table row is replaced in the document the values for the dataset properties retain the old values. I was looking for a way to update the values programmatically which led me to use DOMParser and parseFromString() to attempt to just use the resulting HTMLDocument to pluck out dataset values and use them. Example:

let content1 = `
<div id='div1' class='div-level-1' data-num='12345678'>
  <div id='div2' class='div-level-2'>
    <span id='span1' class='span-class'>
      Span Content
    </span>
  </div>
</div>
`;

let content2 = `
<tr id='tr1' class='row-class' data-num='12345678'>
  <td class='col-class'>
    <span class='col-class'>&nbsp;</span>
  </td>
  <td class='col-class'>
    Some Data in Col 2
  </td>
  <td class='col-class'>
    <a target='_blank' href='http://SomeWebSite.com'>Some Web Site</a>
  </td>
  <td class='col-class'>
    What is going on?
  </td>
</tr>
`;

console.log(content1); // <-- Shows HTML fragment correctly
console.log(content2); // <-- Shows HTML fragment correctly

const parser1 = new DOMParser();
let parsed1 = parser1.parseFromString(content1, 'text/html');
let div1 = parsed1.getElementById('div1');
console.log(div1); // <-- Console shows HTML fragment as expected.
console.log(div1?.dataset?.num); // <-- Console shows 12345678

const parser2 = new DOMParser();
let parsed2 = parser1.parseFromString(content2, 'text/html');
let tr1 = parsed2.getElementById('tr1');
console.log(tr1); // <-- Console shows null.
console.log(tr1?.dataset?.num); // <-- Console shows undefined

Unless I’m nuts, parseFromString() returns gibberish (well, a wrong result anyway) when used on a <tr> element. Using it on a <div> element works as expected: content1 works, k does not. I did not find any info on this. Anyone have ideas? Thanks!

I can’t understand why buttons don’t react on click. trying to make basketball counter on plain JS

Here is piece of HTML and script file there is 3 buttons, each should increase counter on 1,2,3. But this doesn’t work. Plain JS.

const scoreEl = document.querySelectorAll('.score-title');

let count = 0;

function increment() {
  count = count + 1;
  scoreEl.textContent = count;
}

function twoIncrement() {
  count += 2;
  scoreEl.textContent = count;
}

function threeIncrement() {
  count += 3;
  scoreEl.textContent = count;
}
<div class="score">
  <div class="score-title">0</div>
</div>

<div class="button-container">
  <button onclick="increment()" class="btn-score">+1</button>
  <button onclick="twoIncrement()" class="btn-score">+2</button>
  <button onclick="threeIncrement()" class="btn-score">+3</button>
</div>
</div>

Cloudflare Workers Creating Image Collage (Pocessing images)

I’ve been trying to process images using cloudflare workers but everything seems to fail, i know workers are for light tasks only, But i need to process an image, and spicifically fetching 2 images then stack them one on top of the other.

There’s this library called jimp, i could run on workers but in deployment i’m getting cpu time limit exceeded.

How to guarantee that the callback function is called after all the HTML is loaded inside contentDiv?

I have the following Javascript function which intends to load HTML and execute a callback function once the HTML has been loaded.

I would like to clarify if adding text to innerHTML guarantees that the elements will be available in the DOM.

Is the callback function called after all the elements loaded are ready in the DOM in this case or it might be the case it is not?

function loadView(viewId, callback) {

    let contentDiv = document.getElementById('content');
    let url = `${viewId}.html`; // Correctly construct the URL using template literals

    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            // Append the fetched content to contentDiv
            contentDiv.innerHTML += data; 

            // Invoke the callback
            if (typeof callback === 'function') {
                callback();
            }
        })
        .catch(error => {
            console.error('Error loading content:', error);
        });

}

fixing array from being created until button is pressed

I am trying to make a to-do list, I need separate pages one for tasks and one for projects, I have an array that should get filled in once I input a form, but the array gets filled with multiple items after, I have found that every time I click either one of the page buttons, its creating a new array and then the add item button logs all of them, so I am assuming it has to do with how my pages are being loaded or how the code is being ran

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To Do It</title>
</head>
<body>
    <main>
        <div id="side-menu">
            <button id="newBtn">+ New Item</button>
            <form id="formElement" style="display: none;">
                <li>
                    <input type="text" name="title" id="title" placeholder="Task Name">
                </li>
                <li>
                    <input type="text" name="desc" id="desc" placeholder="Description">
                </li>
                <div id="button-options">
                    <li>
                        <select name="priority" id="priority">
                            <option value="priority" selected>Priority</option>
                            <option value="low">Low</option>
                            <option value="medium">Medium</option>
                            <option value="high">High</option>
                        </select>
                    </li>
                    <li>
                        <input type="date" name="dueDate" id="dueDate">
                    </li>
                </div>
                <button id="addBtn" type="submit">Add Item</button>
                <button id="cancelBtn" type="reset">Cancel</button>
            </form>

            <button class="nav-button" id="todayBtn">Home</button>
            <button class="nav-button" id="projectBtn">My Projects</button>
        </div>
        <div id="displayWrapper">
            <ul id="listDisplay" style="display: none;">
                
            </ul>
            <ul id="projectDisplay" style="display: none;">
                
            </ul>
        </div>
    </main>
</body>
</html>

index.js

import './styles.css'; 
import { loadHomePage } from './homePage';
import { loadProjectPage } from './projectPage';

let myList = []; 
let projectList = []; 

document.addEventListener("DOMContentLoaded", () => {

    handlePageChange(loadHomePage, "todayBtn");
    
    document.getElementById("todayBtn").addEventListener("click", () => {
        handlePageChange(loadHomePage, "todayBtn");
    });

    document.getElementById("projectBtn").addEventListener("click", () => {
        handlePageChange(loadProjectPage, "projectBtn");
    });
});

function handlePageChange(loadPageFunction, activeButtonId) {
    document.getElementById("listDisplay").style.display = 'none';
    document.getElementById("projectDisplay").style.display = 'none';

    loadPageFunction();  

    const buttons = document.querySelectorAll(".nav-button");
    buttons.forEach(button => button.classList.remove("selectedMenu"));

    document.getElementById(activeButtonId).classList.add("selectedMenu");
}

export { myList, projectList };

homePage.js

export function loadHomePage() {
    const listDiv = document.getElementById("listDisplay");
    listDiv.style.display = 'block'; 
    listDiv.innerHTML = `<p>Home Page</p>`;  

    let myList = [];

    function listItem(title, description, dueDate, priority) {
        this.title = title;
        this.description = description;
        this.dueDate = dueDate;
        this.priority = priority;
    }

    function listLogic() {
        function displayItem() {
            listDiv.innerHTML = ''; 

            myList.forEach(function(item, index) {
                let itemContainer = document.createElement("div");
                itemContainer.classList.add("item-container");

                let titleElement = document.createElement("p");
                titleElement.textContent = `Title: ${item.title}`;
                itemContainer.appendChild(titleElement);

                let descElement = document.createElement("p");
                descElement.textContent = `Description: ${item.description}`;
                itemContainer.appendChild(descElement);

                let dueDateElement = document.createElement("p");
                dueDateElement.textContent = `Due Date: ${item.dueDate}`;
                itemContainer.appendChild(dueDateElement);

                let priorityElement = document.createElement("p");
                priorityElement.textContent = `Priority: ${item.priority}`;
                itemContainer.appendChild(priorityElement);

                let deleteButton = document.createElement("button");
                deleteButton.classList.add("deleteBtn");
                deleteButton.textContent = "Delete Task";
                itemContainer.appendChild(deleteButton);

                deleteButton.addEventListener("click", function() {
                    myList.splice(index, 1);
                    displayItem();
                });

                listDiv.appendChild(itemContainer);
            });
        }

        function setupFormListener() {
            const formElement = document.getElementById("formElement");

            formElement.removeEventListener("submit", formSubmitHandler);

            function formSubmitHandler(e) {
                e.preventDefault();
                let title = document.getElementById("title").value;
                let desc = document.getElementById("desc").value;
                let priority = document.getElementById("priority").value;
                let dueDate = document.getElementById("dueDate").value;

                const newListItem = new listItem(title, desc, dueDate, priority);
                myList.push(newListItem);
                console.log(myList);

                displayItem();

                document.getElementById('formElement').style.display = 'none';
            }

            formElement.addEventListener("submit", formSubmitHandler);
        }

        setupFormListener();
        return { displayItem };
    }

    function buttonLogic() {
        function newBtn() {
            const newButton = document.getElementById("newBtn");
            newButton.removeEventListener('click', showForm);
            newButton.addEventListener('click', showForm);
        }

        function showForm() {
            document.getElementById('formElement').style.display = 'block';
        }

        function cancelBtn() {
            const cancelButton = document.getElementById('cancelBtn');
            cancelButton.removeEventListener('click', hideForm);
            cancelButton.addEventListener('click', hideForm);
        }

        function hideForm() {
            document.getElementById('formElement').style.display = 'none';
        }

        return { newBtn, cancelBtn };
    }

    const buttonControls = buttonLogic();
    const listControls = listLogic();

    buttonControls.newBtn();
    buttonControls.cancelBtn();
    listControls.displayItem();
}

projectPage.js

export function loadProjectPage() {
    const projectDiv = document.getElementById("projectDisplay");
    projectDiv.style.display = 'block'; 
    projectDiv.innerHTML = `<p>Project Page</p>`; 

    let projectDisplay = [];

    function projectList(title, description, dueDate, priority) {
        this.title = title;
        this.description = description;
        this.dueDate = dueDate;
        this.priority = priority;
    }

    function listLogic() {
        function displayItem() {
            projectDiv.innerHTML = ''; 

            projectDisplay.forEach(function(item, index) {
                let itemContainer = document.createElement("div");
                itemContainer.classList.add("item-container");

                let titleElement = document.createElement("p");
                titleElement.textContent = `Title: ${item.title}`;
                itemContainer.appendChild(titleElement);

                let descElement = document.createElement("p");
                descElement.textContent = `Description: ${item.description}`;
                itemContainer.appendChild(descElement);

                let dueDateElement = document.createElement("p");
                dueDateElement.textContent = `Due Date: ${item.dueDate}`;
                itemContainer.appendChild(dueDateElement);

                let priorityElement = document.createElement("p");
                priorityElement.textContent = `Priority: ${item.priority}`;
                itemContainer.appendChild(priorityElement);

                let deleteButton = document.createElement("button");
                deleteButton.classList.add("deleteBtn");
                deleteButton.textContent = "Delete Task";
                itemContainer.appendChild(deleteButton);

                deleteButton.addEventListener("click", function() {
                    projectDisplay.splice(index, 1);
                    displayItem();
                });

                projectDiv.appendChild(itemContainer);
            });
        }

        function setupFormListener() {
            const formElement = document.getElementById("formElement");

          
            formElement.removeEventListener("submit", formSubmitHandler);

            function formSubmitHandler(e) {
                e.preventDefault();
                let title = document.getElementById("title").value;
                let desc = document.getElementById("desc").value;
                let priority = document.getElementById("priority").value;
                let dueDate = document.getElementById("dueDate").value;

                const newprojectList = new projectList(title, desc, dueDate, priority);
                projectDisplay.push(newprojectList);
                console.log(projectDisplay);

                displayItem();

                document.getElementById('formElement').style.display = 'none';
            }

            formElement.addEventListener("submit", formSubmitHandler);
        }

        setupFormListener();
        return { displayItem };
    }

    function buttonLogic() {
        function newBtn() {
            const newButton = document.getElementById("newBtn");
            newButton.removeEventListener('click', showForm);
            newButton.addEventListener('click', showForm);
        }

        function showForm() {
            document.getElementById('formElement').style.display = 'block';
        }

        function cancelBtn() {
            const cancelButton = document.getElementById('cancelBtn');
            cancelButton.removeEventListener('click', hideForm);
            cancelButton.addEventListener('click', hideForm);
        }

        function hideForm() {
            document.getElementById('formElement').style.display = 'none';
        }

        return { newBtn, cancelBtn };
    }

    const buttonControls = buttonLogic();
    const listControls = listLogic();

    buttonControls.newBtn();
    buttonControls.cancelBtn();
    listControls.displayItem();
}

I can’t really figure out whats happening

How do I insert a table name into a mysql query with ExpressJs?

I’m trying to use this to get contents of a specific table:

let tablename = req.body.login
connection.query('SELECT * FROM ?', tablename, (err, rows) => {
    if (err) throw err
    res.send(rows)
})

But due to tablename being a string, it gets inserted into the query with quotes, resulting in an error. If this can’t work, how can I structure my database to be able to add users and more data to any chosen one?

Discord token grabber

“I am seeking assistance with a script that can extract authentication tokens from Discord. I am specifically interested in a solution that operates within the application itself rather than a script executed via the console. Your help with this would be greatly appreciated.”