Converting png thumbnail to jpg

I have a png thumbnail with base64 data. I am trying to convert it to jpeg thumbnail.
I am not sure what am I doing wrong. My current item has thumbnail data as base64 png.

 var canvas = document.createElement('canvas');
 canvas.id = currItem.Id + '_1';
 canvas.width = currItem.ThumbnailInfo[0].Width;
 canvas.height = currItem.ThumbnailInfo[0].Height;
 var ctx = canvas.getContext('2d');
 ctx!.fillStyle = '#fff';
 var img = new Image();
 img.onload = function () {
     ctx!.drawImage(img, 0, 0, canvas.width, canvas.height);
 }
 img.src = currItem.ThumbnailInfo[0].Thumbnail;
 var imageData = canvas.toDataURL();
 var imagejpeg = canvas.toDataURL('image/jpeg');
 currItem.ThumbnailInfo[0].Thumbnail = imagejpeg;

convert nested for loop to DFS

export function getNameList(nodes: any[]){
let namelist: any[] = []
        for(let node1 of node.schools) {
            if (node1.nodeName === "lanley school") {
                for(let node2 of node1.grades ){
                    if (node2.nodeName === "grade 9"){
                        namelist.push(node2);
                    }
                }
            }
        }
    }
    return namelist;
}

My code is used to walk down a tree to find all students’ names. I want to reduce my code’s runtime by converting the nested for loops to DFS. But I am not sure how to achieve this with two if statements in my code.

How to pass value as prop from another file to function

I want to pass a value from file A to a function in file B that changes with slider input. I am trying to do this by passing the value as a prop.

I am currently getting the error “Expected 1 arguments, but got 0.” when I call GraphArrayFunction() in file B because I am not passing a prop through the function. How would I pass a prop through the function if I want the prop to be able to be changed?
File A:

const test = Number(rangeValue);
GraphArrayFunction({test});

File B:

interface MainProps {
    test: number
}

export const GraphArrayFunction = (props: MainProps) => {
    const {test} = props;
    let i = test 
    const j = 1;
    const graphArray = [];
    //let user change i
    if (i > 1) {
        while (j < i + 1){
            graphArray.push(randomNumber());
            j++;
        }
    }
    return graphArray;
}

const Graph = () => {
    return (
        <Wrapper>
            <GraphOutline>
                {GraphArrayFunction().map((numbers, index) => 
                <HeightBars height={numbers} />)}
            </GraphOutline>
        </Wrapper>
    )
}

export default Graph

How to put values in the object with the user input

here is the code and I would like to put values in the obj using the user input and I’m having troubles.

here is the HTML code that I’m using and I would like to put values in the javascript obj that will be shown in the console.

<div class="container">

    <form>

        <input type="text" id="firstname" placeholder="First Name">
        <input type="text" id="lastname" placeholder="Last Name">

        <select id="gender">
            <option disabled>Select Gender</option>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
        </select>

        <h2>Select Skills:</h2>
        <input type="checkbox" id="htmlskill" value="HyperText Markup Language">
        <label for="htmlskill">HyperText Markup Language</label><br>
        <input type="checkbox" id="cssskill" value="Cascading Style Sheet">
        <label for="cssskill">Cascading Style Sheet</label><br>
        <input type="checkbox" id="jsskill" value="JavaScript">
        <label for="jsskill">JavaScript</label>

        <h2>Select Position:</h2>
        <input type="radio" id="frontend" name="devpos" value="Front-End Developer">
        <label for="frontend">Front-End Developer</label><br>
        <input type="radio" id="backend" name="devpos" value="Back-End Developer">
        <label for="backend">Back-End Developer</label>

        <input type="submit" id="adddev" value="Add Developer">

    </form>

</div>

and here is the javascript code that I would like to use.

window.addEventListener('DOMContentLoaded', function() {

const $ = function(ref) {
    return document.querySelector(ref);
}

const obj = {
    firstname: null,
    lastname: null,
    gender: null,
    skills: [],
    position: null
};

$('#adddev').addEventListener('click', function(e) {

    
    console.log(obj);
});

});

Advice on what tools to use for my website [closed]

I am looking for some advice to further develop my website. I made a classical music quiz which is hosted on Github pages and can be found here: Website. It is written entirely using JavaScript.

My end goal is to have several different quiz modes and highscore lists for each mode. I understand that I will need to get a server to store user highscore data which I intend to do soon.

My question is, is it feasible to develop a fairly complex website simply using JS? Or will it be easier to redo the website using some sort of framework. I am having trouble accomplishing certain things using JS, for example, when the user clicks a new tab while in the middle of a quiz, I want the quiz to halt all processes of the current quiz and launch the new tab from scratch. Basically I need a way to break up the different components of my website instead of one giant JS file. The way I am doing it just not seem feasible.

Any guidance with this would be greatly appreciated. Thanks!

Efficient way of adding an array of new points in Highchart

I am trying to implement a Highchart library with Animation of live updates to a Line-type graph every second using set.interval(). However, as there are 5 data to update, I am currently using 5 unique series and Axis to update the graph while providing users with an option to toggle and view specific selected data.

Current Method – addpoint() for 5 unique series: https://jsfiddle.net/Satientas/6gvxmohd/

  • 5 Series variable (Series_1 Thru Series_5)
  • 5 axis (1 for each Series; so Users can toggle hide/unhide specific Axis to only see certain data)
  • 5 addpoints() method called (1 for each Series)

But even this method doesn’t really work currently, so I am just wondering what is wrong and if there is a more efficient way to do it, maybe using setData()? And is it possible to plot all 5 data in one axis while keeping the toggle hide/unhide series feature?

P.S I am definitely receiving the right JSON result as I have tested that through alert() but I did not include in the fiddlr as I am getting the data through MQTT.

Thanks in advance!

I am trying to print a $0 total to a table if my select box is set to “pickup” and $2 if it is set to “delivery” and then add that to my current total [duplicate]

I figured out how to print the select box options using select.options and [select.selectedIndex] but now I need to print out two results based on which option is selected and then add that to my total. I am not sure if I should be using a loop for this to get the index or if there is another method. I have seen examples of selectedIndex using a for loop but it does not seem to pertain to what I am doing

Here is my code.

function getPizza() {
var total = 0;
    var select = document.getElementById("select_pizza");
    var displaytext = select.options[select.selectedIndex].text;
    document.getElementById("sel_opt").innerHTML = displaytext;

//if structure that I tried using for the index.
if (displaytext.selectedIndex = [0]) {
doucment.getElementById("sel_price").innerHTML += "$0";
}
else
doucment.getElementById("sel_price").innerHTML += "$2";

//total 
total = total + price + top + select;
    document.getElementById("total_result").innerHTML = "Your Current Total is $ " + total;
}

HTML

<select id="select_pizza">
<option value="Pickup">Pick up</option>
<option value="Delivery">Delivery</option> 
</select> 

<table style="width:50%">
<tr>
<th>Description</th>
<th>Option</th>
<th>Price</th>
</tr>

<tr>
<td> Pick-Up/Delivery</td>
<td id="sel_opt"> </td>
<td id="sel_price"> </td>
</tr>
</table>

Any help would be appreciated.

Browser go back to active div in previous page

I want to create a list of button where once clicked, it will shows the respective div as below. And in the div, there is a few links that user can click, and once they clicked the link and go back, it will bring them back to the previous div instead of the first default div. Codes as below.

<div class="tab">
    <a class="tablinks btn" href="#m0" id="t0">Item A</a>
    <a class="tablinks btn" href="#m1" id="t1">Item B</a>
    <a class="tablinks btn" href="#m2" id="t2">Item C</a>
    </div>
    
    <div class="tlist">
    <div id="#m0" class="tdiv" style="display:block;">
    <a href="LinkA.html">LinkA</a></div>
    <div id="#m1" class="tdiv" style="display:none;">
    <a href="LinkB.html">LinkB</a></div>
    <div id="#m2" class="tdiv" style="display:none;">
    <a href="LinkC.html">LinkC</a></div>
    </div>

I have Javascript codes that will change the display from none to block when user clicked on the Item.

document.getElementById("m0").style.display = "block";

document.getElementById("t"+i).addEventListener('click',divStyle.bind(this,"m"+i),false);

function divStyle(num) {
  var i,tdiv,tablinks;
  tdiv = document.getElementsByClassName("tdiv");

  for (i=0;i<tdiv.length;i++) {
    tdiv[i].style.display = "none";
  }
  
  tablinks = document.getElementsByClassName("tablinks");
  
  for (i=0;i<tablinks.length;i++) {
    tablinks[i].className = tablinks[i].className.replace(" active","");
  }
  
  document.getElementById(num).style.display = "block";
  Event.className += "active";
}

The problem I have now is that when LinkC is clicked, and user then pressed Back button in the browser, browser goes back to the link of the previous specific div, for example, page.html#m2 but shows div #m0. I guess this is because I already set document.getElementById("m0").style.display = "block"; by default so it will always go to div #m0 but is there other way to make sure the browser will go back to the previous specific div chosen?

My google finding shows people suggesting history.back() but that means I need to create a Back button but I do not want that. I am sure this is not a complicated issue but I can’t think anymore on how to solve this.
Any help is very appreciated. Thank you!

How do you determine, using RegExp, whether or not a substring is between parentheses?

Might be a duplicate; I thought this question had to have been asked already, but I researched and couldn’t find one.

How do you determine, using RegExp, whether or not a substring is between parentheses?

Say I want to check if the text “fox” is surrounded by parentheses in the following sentence:

The (quick) brown fox jumps (over) the lazy dog.

I tried this RegEx, but it tests true when “fox” is actually not parenthesized but does have parentheses to its left and right:

(.*?fox.*?)

I tried it with negative lookbehind and negative lookahead, and it doesn’t work either:

(.*?(?<!)).*?fox.*?(?!().*?)

User defined renderer object causes a TypeError – marked.js

Right now I’m familiarizing myself with marked.js. I want to add html attributes to the elements that are rendered when marked.parse() is called. In doing so a custom renderer object has been defined which overrides the code method.

When the renderer object is passed to marked.parse(string, {'renderer': renderer}), and I start typing in the TextArea that marked.js is supposed to parse the following error is raised:

  • Uncaught TypeError: t.text is not a function

https://marked.js.org/using_pro#renderer

The renderer defines the HTML output of a given token. If you supply a renderer object to the Marked options, it will be merged with the built-in renderer and any functions inside will override the default handling of that token type.

What is causing this error to be raised?

const renderer = {
  code(code, infoString) {
    return `
      <code class="block_code_snippet fill_block_width">${string}</code
    `
  },
};
post_content_body.addEventListener("keyup", (event) => {
  let marked_post_content = marked.parse(
    post_content_body.value, {"renderer": renderer}
  );
  post_preview.innerHTML = marked_post_content
})

EJS to Webpage Just Downloads File

I am trying to get my ejs files and get it to a website using Vercel, but whenever I click the link, it just downloads the ejs file. How can I get it to open up like a regular html page?

<head>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="login.css">
  <title>Lynx | Login</title>
  <link rel="stylesheet" href="style.css">
</head>

<div class="box">
<div class = "info">
<h1>Login</h1>
<form action="/login" method="POST">
<div>
    <div class = "firstPlace">
  <label for="email">Email</label>
  <input type="email" id="email" name="email" required />
</div>
</div>
<div>
  <div class = "secondPlace">
  <label for="password">Password</label>
  <input type="password" id="password" name="password" required />
</div>
</div>
<button type="submit">Login</button>
</form>
<p class="createAccount">Don't Have an Account?
  Click <a target="_blank" rel="noopener noreferrer" href="/register" class="here">Here</a> to Register.
  </p>
</div>

I tried to create a webpage on Github, but it doesn’t work with EJS and im struggling to implement it on Vercel. Do I need to add another file to read the EJS or something?

Iterate through an array and excecute functions in order javascript

I’m struggling trying to iterate through an array while updating some content(string).
Currently, I have this code:

const replaceUrls = async (content: string) => {
  let allImgsUpdated = 0;
  let newContent = content;
  const oldImgs = content.match(/https?://.*.(?:png|jpg|jpeg|svg|gif)/gi);
  const newImages = ["first", "second"];

  async function firtsFunction(i: number) {
    if (oldImgs) {
      return newContent.replace(`${oldImgs[i]}`, `${newImages[i]}`);
    }
  }

  async function secondFunction() {
    if (oldImgs) {
      for (let i = 0; i < oldImgs?.length; i++) {
        return await firtsFunction(i).finally(() => {
          allImgsUpdated++;
        });
      }
    } else return "not here";
  }

  return await secondFunction().finally(() => {
    if (oldImgs && oldImgs.length >= allImgsUpdated) {
      return newContent;
    } else return "no";
  });
};

My objective is to update the newContent two oldImages urls (this is a test, later I will update the images to be dynamic to how much ‘oldImages’ I have) to the new ones. But when I run this code, only the first one updates. Can somebody help me here? thanks

CSS rookie not understanding grids and flex setup (Creating a wordle game for my friends)

I was following a youtube tutorial on how to create your own Wordle game. In that video they follow the strict 5 letter words that Wordle plays by. I want my game to have words of length 4-7.

When I changed the length from 5 to varying my character boxes went vertical:
Screenshot

// Tutorial: https://www.youtube.com/watch?v=j7OhcuZQ-q8
document.addEventListener("DOMContentLoaded", () => {
    let word = "dairy";
    impactleWord();
    createSquares();

    let guessedWords = [
        []
    ];

    let availableSpace = 1;


    let guessedWordCount = 0;

    const keys = document.querySelectorAll('.keyboard-row button');

    function impactleWord() {
        let wordLibrary = [];
        let s = "impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense,impact,sample,four,fives,sixsix,sevense";
        wordLibrary = s.split(',');
        const d = new Date();
        let impactleDay = Math.round((d.getTime() / 1000 - 1648360800) / 86400);
        word = wordLibrary[impactleDay];
        document.documentElement.style.setProperty(`--cols`, `'${word.length}'`);
        // window.alert(word); // TODO: Delete -> Debugging purposes only
    }

    function getCurrentWordArr() {
        const numberOfGuessedWords = guessedWords.length;
        return guessedWords[numberOfGuessedWords - 1];
    }

    function updateGuessedWords(letter) {
        const currentWordArr = getCurrentWordArr();
        if (currentWordArr && currentWordArr.length < word.length) {
            currentWordArr.push(letter);

            const availableSpaceEl = document.getElementById(String(availableSpace));
            availableSpace = availableSpace + 1;

            availableSpaceEl.textContent = letter;
        }
    }

    function getTileColor(letter, index) {
        const isCorrectLetter = word.includes(letter);

        if (!isCorrectLetter) {
            return "rgb(58, 58, 60)";
        }

        const letterInThatPosition = word.charAt(index);
        const isCorrectPosition = (letter === letterInThatPosition);

        if (isCorrectPosition) {
            return "rgb(83, 141, 78)";
        }

        return "rgb(181, 159, 59)";
    }

    function handleSubmitWord() {
        const currentWordArr = getCurrentWordArr();
        if (currentWordArr.length !== word.length) {
            window.alert("Word must be 5 letters");
        }

        const currWord = currentWordArr.join('');

        const firstLetterId = guessedWordCount * word.length + 1;
        const interval = 200;
        currentWordArr.forEach((letter, index) => {
            setTimeout(() => {
                const tileColor = getTileColor(letter, index);

                const letterId = firstLetterId + index;
                const letterEl = document.getElementById(letterId);
                letterEl.classList.add("animate__flipInX");
                letterEl.style = `background-color:${tileColor};border-color:${tileColor}`;
            }, interval * index);
        });

        guessedWordCount += 1;

        if (currWord === word) {
            window.alert("Great success!");
        }

        if (guessedWords.length === word.length + 1) {
            window.alert(`Game over! The word is ${word}.`);
        }

        guessedWords.push([]);
    }

    function createSquares() {
        const gameBoard = document.getElementById("board");

        for (let index = 0; index < word.length * (word.length + 1); index++) {
            let square = document.createElement("div");
            square.classList.add("square");
            square.classList.add("animate__animated");
            square.setAttribute("id", index + 1);
            gameBoard.appendChild(square);
        }
    }

    for (let i = 0; i < keys.length; i++) {
        keys[i].onclick = ({ target }) => {
            const letter = target.getAttribute("data-key");

            if (letter === 'enter') {
                handleSubmitWord();
                return;
            }
            updateGuessedWords(letter);
        }
    }
});
* {
    margin: 0;
    padding: 0;
}

html,
body {
    height: 100%;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

#container {
    display: flex;
    background-color: black;
    height: 100%;
    align-items: center;
    flex-direction: column;
}

#game {
    width: 100%;
    max-width: 500px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

header {
    border-bottom: 1px solid rgb(58, 58, 60);
}

.title {
    color: gainsboro;
    font-size: 2.5rem;
    font-weight: bold;
    margin: 0.4rem 0 0.4rem 0;
    text-align: center;
    text-transform: uppercase;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

#board-container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-grow: 1;
    overflow: hidden;
}

#board {
    display: grid;
    grid-template-columns: repeat(var(--cols), 1fr);
    grid-gap: 5px;
    padding: 10px;
    box-sizing: border-box;
}

.square {
    border: 2px solid rgb(58, 58, 60);
    min-width: 60px;
    min-height: 60px;
    font-size: 44px;
    font-weight: bold;
    color: gainsboro;
    text-transform: uppercase;
    display: flex;
    justify-content: center;
    align-items: center;
}

#keyboard-container {
    height: 200px;
}

.keyboard-row {
    display: flex;
    justify-content: center;
    width: 100%;
    margin: 0 auto 8px;
    touch-action: manipulation;
}

.keyboard-row button {
    font-family: inherit;
    font-weight: bold;
    border: 0;
    padding: 0;
    height: 58px;
    cursor: pointer;
    background-color: rgb(129, 131, 132);
    color: rgb(215, 218, 220);
    flex-grow: 1;
    text-transform: uppercase;
    margin-right: 6px;
    border-radius: 4px;
    user-select: none;
}

.keyboard-row button.wide-button {
    flex-grow: 1.5;
}

.spacer-half {
    flex-grow: 0.5;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Worlde For Friends</title>

    <script src="js/main.js"></script>

    <link rel="stylesheet" href="css/styles.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
</head>

<body>
    <div id="container">
        <div id="game">
            <header>
                <h1 class="title">Friendle</h1>
            </header>

            <div id="board-container">
                <div id="board"></div>
            </div>

            <div id="keyboard-container">
                <div class="keyboard-row">
                    <button data-key="q">q</button>
                    <button data-key="w">w</button>
                    <button data-key="e">e</button>
                    <button data-key="r">r</button>
                    <button data-key="t">t</button>
                    <button data-key="y">y</button>
                    <button data-key="u">u</button>
                    <button data-key="i">i</button>
                    <button data-key="o">o</button>
                    <button data-key="p">p</button>
                    <div class="spacer-half"></div>
                </div>

                <div class="keyboard-row">
                    <button data-key="a">a</button>
                    <button data-key="s">s</button>
                    <button data-key="d">d</button>
                    <button data-key="f">f</button>
                    <button data-key="g">g</button>
                    <button data-key="h">h</button>
                    <button data-key="j">j</button>
                    <button data-key="k">k</button>
                    <button data-key="l">l</button>
                    <div class="spacer-half"></div>
                </div>

                <div class="keyboard-row">
                    <button data-key="enter" class="wide-button">Enter</button>
                    <button data-key="z">z</button>
                    <button data-key="x">x</button>
                    <button data-key="c">c</button>
                    <button data-key="v">v</button>
                    <button data-key="b">b</button>
                    <button data-key="n">n</button>
                    <button data-key="m">m</button>
                    <button data-key="del" class="wide-button">Del</button>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

Any explanation as to what is going wrong with the spacing and grid is much appreciated.

How I can show a If statement result in a table made in HTML

The table image
I created a table about grading students, they have their names and grades arranged in a array and sorted by alphabetical order. So I need to show if they passed or not from their grades, I made a if statement to make it show but it’s not showing on the table and on the console marks that the i in var grade = alumno[i][1]; is not defined. How I can define it?

var alumno = [{name: "Max", grade: 95, appr},
            {name: "Isabella", grade: 90, appr},
            {name: "Leo", grade: 60, appr},
            {name: "María", grade: 73, appr},
            {name: "Andres", grade: 100, appr},
            {name: "Danna", grade: 87, appr},
            {name: "Alan", grade: 70, appr},
            {name: "Roberta", grade: 67, appr},
            {name: "Eugenio", grade: 99, appr},
            {name: "Regina", grade: 100, appr},]

            alumno.sort(function (a, b) {
                const nameA = a.name.toUpperCase();
                const nameB = b.name.toUpperCase();
                if (nameA < nameB) {
                    return -1;
                }
                if (nameA > nameB) {
                    return 1;
                }
                return 0;
            });

var table = document.getElementById("myTable");
var rows =  table.querySelectorAll('tr');
for (let i = 1; i < rows.length; i++) {
    rows[i].children[0].textContent = alumno[i-1].name
    rows[i].children[1].textContent = alumno[i-1].grade
    rows[i].children[2].textContent = alumno[i-1].appr
}

var appr;
var grade = alumno[i][1];
if (grade >=70) {
    appr = 'Aprobado';
} else if (grade <=69) {
    appr = 'Esfuérzate más';
}