Button Counters HTML5 & Javascript

I have a clicker-type game coded in HTML5 and javascript which has upgrade buttons. I’ve made it so these buttons increase in price on each click, and show the price. The problem is that it shows the price of the previous upgrade, not the next one. This makes it so you can’t actually see the price of the upgrade which you are about to buy.

Code :

`
let buttonUpgradeElem = document.querySelector(‘.upGradeA’);

        let cost = 20;

        updateButtonDisplay();

        buttonUpgradeElem.addEventListener("click", () => {

            cost = 1.05 * cost;
            count = count - cost;
            updateButtonDisplay();
            updateDisplay();

            counterPlusElem.addEventListener("click", () => {

                count = count + 1;
                updateDisplay();

            });
        });

        function updateButtonDisplay() {
            buttonUpgradeElem.innerHTML = "+ 1 per click Cost : $" + cost;
        };

`

I tried adding another EventListener, I thought it might solve the problem. It didn’t end up solving the problem.

My hexagon highlight function creates an oval; not a circle: how might I fix it?

I have an issue with my JavaScript. I’m trying to write a highlight function which highlights a circle of hexagons around a clicked hexagon at a given radius. Initially, I was able to get it to do, first a cross, followed by a square, and now I’ve got an oval happening.

I understand that it’s due to the offsets of the hexagons that seems to be the most likely cause of the problem. As of yet, I have been unable to solve my ovular problem; however, at least it’s a step beyond square. Well, at least a bit more round. While at larger sizes the oval is livable for now, it is most definitely not desired. Any help with pointing me in the right direction to solve this issue would most appreciated. My code follows.

map.php: the hexagon grid.

<div id="gamecontent">
<div id="main">
    <div id="container">
<div id='0' name='0,0' value='0,-11,11' class='space axis'>0,0</div>
<div id='1' name='1,0' value='1,-11,10' class='space'>1,0</div>
<div id='2' name='2,0' value='2,-11,9' class='space'>2,0</div>
<div id='3' name='3,0' value='3,-11,8' class='space'>3,0</div>
<div id='4' name='4,0' value='4,-11,7' class='space'>4,0</div>
<div id='5' name='5,0' value='5,-11,6' class='space'>5,0</div>
<div id='6' name='6,0' value='6,-11,5' class='space'>6,0</div>
<div id='7' name='7,0' value='7,-11,4' class='space'>7,0</div>
<div id='8' name='8,0' value='8,-11,3' class='space'>8,0</div>
<div id='9' name='9,0' value='9,-11,2' class='space'>9,0</div>
<div id='10' name='10,0' value='10,-11,1' class='space'>10,0</div>
<div id='11' name='11,0' value='11,-11,0' class='space axis'>11,0</div>

<br />

<div id='12' name='0,1' value='0,-10,10' class='space axis'>0,1</div>
<div id='13' name='1,1' value='1,-10,9' class='space'>1,1</div>
<div id='14' name='2,1' value='2,-10,8' class='space'>2,1</div>
<div id='15' name='3,1' value='3,-10,7' class='space'>3,1</div>
<div id='16' name='4,1' value='4,-10,6' class='space'>4,1</div>
<div id='17' name='5,1' value='5,-10,5' class='space'>5,1</div>
<div id='18' name='6,1' value='6,-10,4' class='space'>6,1</div>
<div id='19' name='7,1' value='7,-10,3' class='space'>7,1</div>
<div id='20' name='8,1' value='8,-10,2' class='space'>8,1</div>
<div id='21' name='9,1' value='9,-10,1' class='space'>9,1</div>
<div id='22' name='10,1' value='10,-10,0' class='space axis'>10,1</div>
<div id='23' name='11,1' value='11,-10,-1' class='space'>11,1</div>

<br />

<div id='24' name='0,2' value='0,-9,9' class='space axis'>0,2</div>
<div id='25' name='1,2' value='1,-9,8' class='space'>1,2</div>
<div id='26' name='2,2' value='2,-9,7' class='space'>2,2</div>
<div id='27' name='3,2' value='3,-9,6' class='space'>3,2</div>
<div id='28' name='4,2' value='4,-9,5' class='space'>4,2</div>
<div id='29' name='5,2' value='5,-9,4' class='space'>5,2</div>
<div id='30' name='6,2' value='6,-9,3' class='space'>6,2</div>
<div id='31' name='7,2' value='7,-9,2' class='space'>7,2</div>
<div id='32' name='8,2' value='8,-9,1' class='space'>8,2</div>
<div id='33' name='9,2' value='9,-9,0' class='space axis'>9,2</div>
<div id='34' name='10,2' value='10,-9,-1' class='space'>10,2</div>
<div id='35' name='11,2' value='11,-9,-2' class='space'>11,2</div>

<br />

<div id='36' name='0,3' value='0,-8,8' class='space axis'>0,3</div>
<div id='37' name='1,3' value='1,-8,7' class='space'>1,3</div>
<div id='38' name='2,3' value='2,-8,6' class='space'>2,3</div>
<div id='39' name='3,3' value='3,-8,5' class='space'>3,3</div>
<div id='40' name='4,3' value='4,-8,4' class='space'>4,3</div>
<div id='41' name='5,3' value='5,-8,3' class='space'>5,3</div>
<div id='42' name='6,3' value='6,-8,2' class='space'>6,3</div>
<div id='43' name='7,3' value='7,-8,1' class='space'>7,3</div>
<div id='44' name='8,3' value='8,-8,0' class='space axis'>8,3</div>
<div id='45' name='9,3' value='9,-8,-1' class='space'>9,3</div>
<div id='46' name='10,3' value='10,-8,-2' class='space'>10,3</div>
<div id='47' name='11,3' value='11,-8,-3' class='space'>11,3</div>

<br />

<div id='48' name='0,4' value='0,-7,7' class='space axis'>0,4</div>
<div id='49' name='1,4' value='1,-7,6' class='space'>1,4</div>
<div id='50' name='2,4' value='2,-7,5' class='space'>2,4</div>
<div id='51' name='3,4' value='3,-7,4' class='space'>3,4</div>
<div id='52' name='4,4' value='4,-7,3' class='space'>4,4</div>
<div id='53' name='5,4' value='5,-7,2' class='space'>5,4</div>
<div id='54' name='6,4' value='6,-7,1' class='space'>6,4</div>
<div id='55' name='7,4' value='7,-7,0' class='space axis'>7,4</div>
<div id='56' name='8,4' value='8,-7,-1' class='space'>8,4</div>
<div id='57' name='9,4' value='9,-7,-2' class='space'>9,4</div>
<div id='58' name='10,4' value='10,-7,-3' class='space'>10,4</div>
<div id='59' name='11,4' value='11,-7,-4' class='space'>11,4</div>

<br />

<div id='60' name='0,5' value='0,-6,6' class='space axis'>0,5</div>
<div id='61' name='1,5' value='1,-6,5' class='space'>1,5</div>
<div id='62' name='2,5' value='2,-6,4' class='space'>2,5</div>
<div id='63' name='3,5' value='3,-6,3' class='space'>3,5</div>
<div id='64' name='4,5' value='4,-6,2' class='space'>4,5</div>
<div id='65' name='5,5' value='5,-6,1' class='space'>5,5</div>
<div id='66' name='6,5' value='6,-6,0' class='space axis'>6,5</div>
<div id='67' name='7,5' value='7,-6,-1' class='space'>7,5</div>
<div id='68' name='8,5' value='8,-6,-2' class='space'>8,5</div>
<div id='69' name='9,5' value='9,-6,-3' class='space'>9,5</div>
<div id='70' name='10,5' value='10,-6,-4' class='space'>10,5</div>
<div id='71' name='11,5' value='11,-6,-5' class='space'>11,5</div>

<br />

<div id='72' name='0,6' value='0,-5,5' class='space axis'>0,6</div>
<div id='73' name='1,6' value='1,-5,4' class='space'>1,6</div>
<div id='74' name='2,6' value='2,-5,3' class='space'>2,6</div>
<div id='75' name='3,6' value='3,-5,2' class='space'>3,6</div>
<div id='76' name='4,6' value='4,-5,1' class='space'>4,6</div>
<div id='77' name='5,6' value='5,-5,0' class='space axis'>5,6</div>
<div id='78' name='6,6' value='6,-5,-1' class='space'>6,6</div>
<div id='79' name='7,6' value='7,-5,-2' class='space'>7,6</div>
<div id='80' name='8,6' value='8,-5,-3' class='space'>8,6</div>
<div id='81' name='9,6' value='9,-5,-4' class='space'>9,6</div>
<div id='82' name='10,6' value='10,-5,-5' class='space'>10,6</div>
<div id='83' name='11,6' value='11,-5,-6' class='space'>11,6</div>

<br />

<div id='84' name='0,7' value='0,-4,4' class='space axis'>0,7</div>
<div id='85' name='1,7' value='1,-4,3' class='space'>1,7</div>
<div id='86' name='2,7' value='2,-4,2' class='space'>2,7</div>
<div id='87' name='3,7' value='3,-4,1' class='space'>3,7</div>
<div id='88' name='4,7' value='4,-4,0' class='space axis'>4,7</div>
<div id='89' name='5,7' value='5,-4,-1' class='space'>5,7</div>
<div id='90' name='6,7' value='6,-4,-2' class='space'>6,7</div>
<div id='91' name='7,7' value='7,-4,-3' class='space'>7,7</div>
<div id='92' name='8,7' value='8,-4,-4' class='space'>8,7</div>
<div id='93' name='9,7' value='9,-4,-5' class='space'>9,7</div>
<div id='94' name='10,7' value='10,-4,-6' class='space'>10,7</div>
<div id='95' name='11,7' value='11,-4,-7' class='space'>11,7</div>

<br />

<div id='96' name='0,8' value='0,-3,3' class='space axis'>0,8</div>
<div id='97' name='1,8' value='1,-3,2' class='space'>1,8</div>
<div id='98' name='2,8' value='2,-3,1' class='space'>2,8</div>
<div id='99' name='3,8' value='3,-3,0' class='space axis'>3,8</div>
<div id='100' name='4,8' value='4,-3,-1' class='space'>4,8</div>
<div id='101' name='5,8' value='5,-3,-2' class='space'>5,8</div>
<div id='102' name='6,8' value='6,-3,-3' class='space'>6,8</div>
<div id='103' name='7,8' value='7,-3,-4' class='space'>7,8</div>
<div id='104' name='8,8' value='8,-3,-5' class='space'>8,8</div>
<div id='105' name='9,8' value='9,-3,-6' class='space'>9,8</div>
<div id='106' name='10,8' value='10,-3,-7' class='space'>10,8</div>
<div id='107' name='11,8' value='11,-3,-8' class='space'>11,8</div>

<br />

<div id='108' name='0,9' value='0,-2,2' class='space axis'>0,9</div>
<div id='109' name='1,9' value='1,-2,1' class='space'>1,9</div>
<div id='110' name='2,9' value='2,-2,0' class='space axis'>2,9</div>
<div id='111' name='3,9' value='3,-2,-1' class='space'>3,9</div>
<div id='112' name='4,9' value='4,-2,-2' class='space'>4,9</div>
<div id='113' name='5,9' value='5,-2,-3' class='space'>5,9</div>
<div id='114' name='6,9' value='6,-2,-4' class='space'>6,9</div>
<div id='115' name='7,9' value='7,-2,-5' class='space'>7,9</div>
<div id='116' name='8,9' value='8,-2,-6' class='space'>8,9</div>
<div id='117' name='9,9' value='9,-2,-7' class='space'>9,9</div>
<div id='118' name='10,9' value='10,-2,-8' class='space'>10,9</div>
<div id='119' name='11,9' value='11,-2,-9' class='space'>11,9</div>

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

map.css: the css for the grid.

* {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor:default;
}
#gamecontent {
    border:1px solid #000000;
    background-color:#000000;
    position:fixed;
    color:#a6a6a6;
    top:11.5%;
    left:50%;
    border-radius:30px;
    transform:translateX(-50%);
    width:88%;
    height:86%;
    overflow:hidden;
    z-index:100;
    visibility:visible;
}
#main {
    border:0px solid steelblue;
    color:#afafaf;
    position: fixed;
    top:0;
    left:50%;
    border-radius:30px;
    transform:translateX(-50%);
    width:100%;
    height:100%;
    overflow:hidden;
    border-bottom:none;
    visibility:visible;
    z-index:99999;
}
#container {
    --s: 26px;
    --m: 1.5px;
    --f: calc(1.732 * var(--s) + 12 * var(--m)  - 13px);

    position: relative;
    
    margin-left:auto;
    margin-right:auto;
    
    width:100%;
    height:100%;
    border:0px solid cyan;
    font-size: 0;
    z-index:300;
    overflow:hidden;
    padding:1%;
    padding-left:1.8%;
    padding-top:1.5%;
}
#container::before {
    content: "";
    width: calc(var(--s)/2 + var(--m));
    float: left;
    height: 110%;
    shape-outside: repeating-linear-gradient(
                       #0000 0 calc(var(--f) - 10px),
                       #000  0 var(--f));
}
.space {
    /* left:-6%; */
    transform:translateX(6%);
    text-align: center;
    line-height:20px;
    font-size:xx-small;
    width: var(--s);
    margin: var(--m);
    height: calc(var(--s)*1.1547);
    display: inline-block;
    clip-path: polygon(0% 25%, 0% 75%, 50% 100%, 100% 75%, 100% 25%, 50% 0%);
    background-color: rgba(69, 69, 69, 0.50);
    margin-bottom: calc(var(--m) - var(--s)*0.2885);
    z-index:300;
}

map.js: my current JavaScript with the oval problem.

var spacetiles = document.getElementsByClassName("space");
var totaltiles=spacetiles.length;
var size=3;
var i=0;

var lrow=getrowlength(spacetiles);
var srow=lrow-1;

var highlightcolor="rgba(85,136,238,0.50)";
var spacecolor="rgba(85, 85, 85, 0.5)";

var ycount=size-1;
var xcount=size-1;

for (i = 0; i < totaltiles; i++) {
    spacetiles[i].addEventListener('click', function() {
        highlight(this,size);
    }, false);
}

function getrowlength(spacetiles) {
    var tilecount=0;
    while (parseInt(spacetiles[i].getAttribute("name").split(",")[1])<1) {
        tilecount=tilecount+1;
        i=i+1;
    }
    return tilecount;
}

function clearselect() {
    for (i = 0; i < this.totaltiles; i++) {
        if (this.spacetiles[i].classList.contains("space")) {
            this.spacetiles[i].style.backgroundColor=spacecolor;
        }
    }
}

function highlight(tile,size) {
clearselect();

var centerX=parseInt(tile.getAttribute("name").split(",")[0]);
var centerY=parseInt(tile.getAttribute("name").split(",")[1]);

for (i=0;i<totaltiles;i++) {
    var currentTile=spacetiles[i];
    var x=parseInt(currentTile.getAttribute("name").split(",")[0]);
    var y=parseInt(currentTile.getAttribute("name").split(",")[1]);

        if (Math.max(Math.abs(x-centerX),Math.abs(y-centerY),Math.abs(x+y-centerX-centerY))<=size) {
            currentTile.style.backgroundColor=highlightcolor;
        }
    }
}

A CodePen with my most current code can be found here:

Hex Selection (Oval Issue)

Thanks for taking the time to view this. I look forward to any responses.

The presented code is a progression of attempts to get a circular highlight. First, I managed a cross. Then a square; now and oval. I hope to remedy this issue soon.

setTimeout with text AND ? getting [object Object]

Im trying to set useState/timeout to display text and an icon image after 5 seconds, text is fine but i want to be able to also have an image:

import slackbot from '../../public/images/slackbot.png'

const [text, setText] = useState('')

useEffect(() => {
  const timeout = setTimeout(() => {
    setText( {slackbot} + 'this will be the slackbot auto message' )
  }, 3000)
}, [])

attempting to add it in the use State set Text as shown above but leaves me with an [object Object] display.

HTML elements move when page is refreshed or link is clicked

I am working on a website for my friend and for some reason that I can not figure out the styling gets all messed up when you refresh the site multiple times quickly or when you open a link. I have included before and after images so you can see what I mean. I’ve been trying to search the internet for answers to why this is happening but I can not find anything so if anyone can take a look at my code and tell me what is wrong it would be much appreciated.

function openDistance() {
        var div = document.getElementById("distance-popup");
        div.style.display = "block";
    }
    function closeDistance() {
        var div = document.getElementById("distance-popup");
        div.style.display = "none";
    }
html{
    scroll-behavior: smooth;
    overflow-x: hidden;
    scrollbar-color: #070600 #5C6672;
}
body {
    background-image: url(./images/BAKER background.jpg);
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
}

.top {
    position: relative;
    height: 100vh;
}


.bigtitle {
    text-align: center;
    color: #A52A2A;
    font-size: 16.1vw;
}

.nav {
    position: relative;
    top: 30vh;
    display: flex;
    align-items: flex-start;
    height: 100vh;
}

#releases {
    left: 30%;
    top: 0;
    margin-left: -60px;
}
  
#about  {
    left: 80%;
    top: 20%;
    margin-left: -80px;
}
  
#meet {
    left: 30%;
    top: 40%;
    margin-left: -60px;
}
  
#socials {
    left: 80%;
    top: 60%;
    margin-left: -70px;
}
  

.nav a {
    font-size: 3vw;
    transition: font-size 0.3s ease-in-out;
    color: #A52A2A;
    position: absolute;
    top: 50%;
    left: 50%; /* Adjust the horizontal position */
    transform: translate(-50%, -50%);
    margin-left: -50px;
    text-decoration: none;
    height: 7.5vh; /* Fixed height for the links */
    overflow: hidden; /* Prevents content from overflowing */
}

.nav a:hover {
    font-size: 3.3vw;
}

.aboutme {
    position: relative;
    top: 20vh;
    left: 50%;
    transform: translateX(-50%);
    width: 100vw;
    height: 110vh;
    background-color: #070600;
    background-size: cover;
  }



.aboutme p {
    color: #F4F2F2;
    text-align: center;
    padding: 20px;
}

.blank{
    position: relative;
    top: 20vh;
    display: flex;
    align-items: flex-start;
    height: 100vh;
}

.content {
    position: relative;
    top: 20vh;
    left: 50%;
    transform: translateX(-50%);
    width: 100vw;
    height: 110vh;
    background:rgba(7, 6, 0, 0.95);
    background-size: cover;
    overflow: hidden;
  }

.carousel{
    max-width: 60vw;
    margin: 0 auto;
    overflow: hidden;
}
.carousel_items{
    display: inline-block;
    animation: carousel 8s linear infinite;
    white-space: nowrap;
}
.carousel_img{
    display: inline-block;
    width: 50vh;
    height: 50vh;
    object-fit: cover;
    padding: 10px;
}

@keyframes carousel {
    0% {
        transform: translateX(0%);
      }
      100% {
        transform: translateX(-50%);
      }
}

.carousel_img:hover{
    transform: scale(1.1);
}

.title{
    color: #a52a2a;
    font-size: 3vw;
    text-align: center;
    padding: 20px;
    margin-left: 20%;
    margin-right: 20%;
    margin-top: 2%;
    user-select: none;
}

.popup .title{
    color: #a52a2a;
    font-size: 3vw;
    text-align: center;
    padding: 20px;
    margin-left: 20%;
    margin-right: 20%;
    user-select: none;
    z-index: 3;
}

.popup {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 55%;
    height: 95%;
    background-color: #070600;

    z-index: 2;
}

.popup img{
    width: 50vh;
    height: auto;
    margin: auto;
    display: block;
}
.links{
    margin: auto;
    width: 50vh;
    height: 6vh;
    padding: 10px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
}
.links a {
    display: flex;
    align-items: center;
}
.links a img{
    padding: 10px;
    width: 5vh;
}
.links a img:hover{
    transform: scale(1.1);
}
.x-button {
    display: inline-block;
    padding: 5px 10px;
    background-color: #5C6672;
    color: #F4F2F2;
    border: none;
    font-size: 14px;
    font-weight: bold;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .x-button:hover {
    transform: scale(1.1);
  }
  
  .x-button:focus {
    outline: none;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="baker.css">
    <title>BAKER!</title>
</head>

<body>
    <div id="top">
        <p class="bigtitle">BAKER!</p>
    </div>
    

    <div class="nav"> 
        <a id="releases" href="#newreleases_title">My Projects!</a>
        <a id="about" href="#aboutme_title">About Me!</a>
        <a id="meet" href="#meetthecrew_title">The Kitchen Crew!</a>
        <a id="socials" href="#socials_title">My Socials!</a>
    </div>

    <div class="content">
        <h1 class="title" id="newreleases_title">My Projects!</h1>

        <div class="carousel">
            <div class="carousel_items">
                <img src="images/distance.JPEG" class="carousel_img" onclick="openDistance()">
                <img src="images/Mi amor.jpeg" class="carousel_img">
                <img src="images/overandupcover.jpg" class="carousel_img">
                <!--REPEAT IMAGES-->
                <img src="images/distance.JPEG" class="carousel_img" onclick="openDistance()">
                <img src="images/Mi amor.jpeg" class="carousel_img">
                <img src="images/overandupcover.jpg" class="carousel_img">
            </div>

        </div>
    </div>

    <div class="popup" id="distance-popup">
        <button class="x-button" onclick="closeDistance()">X</button>
        <h1 class="title">Distance</h1>
        <img class="image" src="./images/distance.JPEG">
        <div class="links">
            <a href="https://open.spotify.com/track/1MiaGK2uKor5ZyKiu0CFEv?si=c264150192034dbd" target="_blank"><img class="logo" src="./images/spotify.png"></a>
            <a href=""target="_blank"><img class="logo" src="./images/applemusic.png"></a>
        </div>
    </div>

    <div class="blank"></div>

    <div class="content"> 
        <h1 class="title" id="aboutme_title">About Me!</h1>
    </div>

    <div class="blank"></div>

    <div class="content"> 
        <h1 class="title" id="meetthecrew_title">The Kitchen Crew!</h1>
    </div>

    <div class="blank"></div>

    <div class="content"> 
        <h1 class="title" id="socials_title">My Socials!</h1>
    </div>

</body>
</html>

I was not sure how to add in the images if that is even an option in this editor. I am also using the latest version of Google Chrome to test the site.

Intended look before refreshing or leaving the site

Messed up look after refreshing or leaving the site

Freecodecamp D3 visualization project

Im working on the data visualization project 1; Bar chart. Im using the codepen IDE as suggested in the exercise.

My code is compiling and data is being fetched (I can view it in the console) and there are no errors but my code isn’t being rendered.

My code so far:

function App() {
const [gdp, setGdpData] = React.useState();
React.useEffect(() => {
async function fetchData() {
const response = await fetch(“https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json”
);
const data = await response.json();
console.log(data);
setGdpData(data);
}
fetchData();
}, []);

return (

) }
function barChart({data, height, width, widthOfBar}) {
React.useEffect(() => {
createBarChart();
[data]);

const createBarChart = () => {
const gdp = data.map((dataPoint) => dataPoint[1]);
const year = data.map((year) => year[0]);

const gdpMax = d3.max(gdp);
const yScale = d3.scaleLinear().domain([0, gdpMax]).range([0, height]);
d3.select(‘svg’).selectAll(“rect”).data(gdp).enter().append(“rect”);
d3.select(‘svg’).selectAll(“rect”).data(gdp).style(“fill”, “#9595ff”)
.attr(“x”, (d, i) => i*widthOfBar)
.attr(“y”, (d) => height -yScale(d + gdpMax * 0.1))
.attr(“height”, (d,i) => yScale(d + gdpMax * 0.1))
.attr(“width”, widthOfBar);
};
return (
<>
svg width={width} height={height}>
<
);
}
const root = ReactDOM.createRoot(document.getElementById(“app”));
root.render();

Encapsulate document fragments using JS

I want to create a simple code mirror that renders HTML and CSS codes written in two elements and shows the result below them.
A very simplified code of what I want:

const headEle= document.querySelector("head");
const cssCode= document.querySelector(".code--css");
const htmlCode= document.querySelector(".code--html");

const styleEle= document.createElement("style");
const resultEle= document.createElement("div");

headEle.appendChild(styleEle);
styleEle.innerHTML= cssCode.innerHTML;

resultEle.innerHTML= htmlCode.innerHTML. replace(/&lt;/g,'<').replace(/&gt;/g,'>');
resultEle.className= "code code--result";

htmlCode. insertAdjacentElement("afterend",resultEle)
p {color:red}

.code {
  background-color:lightsteelblue;
  line-height: 1.6;
  padding: 8px
}
.code::before {
  display: block;
  font-weight: bold;
}
.code--css::before {
  content: "CSS:"
}
.code--html::before {
  content: "HTML:"
}
.code--result {
  background-color:transparent;
  border: solid 1px black
}
.code--result::before {
  content: "Result:";
}
<pre class="code code--css">
p {color:blue}</pre>

<pre class="code code--html">
&lt;p>Lorem ipsum&lt;/p></pre>

<p>Lorem ipsum</p>

I have found the following code but I’m junior in JS and don’t know how to implement it for my purpose.
I have checked a lot of documentation about “Web Components”, “shodowDOM”, “document fragment” but I couldn’t find any simple way at my level of information. (they include extending HTMLElements by using classes and so on)
I don’t know where to start reading about this subject and I would appreciate it if you could show me a road map and give me a general explanation.

const templateEle= document.querySelector("template").content;
const sectionEle= document.querySelector("section");

sectionEle.attachShadow({mode:"open"}). appendChild(templateEle.cloneNode(true));
p {color: red}
<template>
  <style>
    p {color: blue}
  </style>
  <p>Lorem ipsum</p>
</template>

<section></section>
<p>Lorem ipsum</p>

Make specific letter appear in a different colour inside one

I have a website that has a command-line-like animation, meaning it types a phrase when I refresh it. It works properly, but I would like to have certain letters (XYZ) appear in neon pink. I tried to make it work in many ways but simply couldn’t do it. Anyone knows how to do it?
Here is the code:

<!DOCTYPE html>
<html>
<head>
  <title>Sample website</title>
  <style>
    body {
      font-family: monospace;
      background-color: black;
      color: white;
      text-align: center;
      margin-top: 21%;
    }

    .neon-pink {
      color: #ff00ff; /* Neon Pink color code */
    }

    .hidden {
      display: none;
      visibility: hidden;
    }

    /* ----- blinking cursor animation ----- */
    .typed-cursor{
      opacity: 1;
      -webkit-animation: blink 0.95s infinite;
      -moz-animation: blink 0.95s infinite;
      -ms-animation: blink 0.95s infinite;
      -o-animation: blink 0.95s infinite;
      animation: blink 0.95s infinite;
    }

    @keyframes blink {
      0% { opacity:1; }
      50% { opacity:0; }
      100% { opacity:1; }
    }

    @-webkit-keyframes blink {
      0% { opacity:1; }
      50% { opacity:0; }
      100% { opacity:1; }
    }

    @-moz-keyframes blink {
      0% { opacity:1; }
      50% { opacity:0; }
      100% { opacity:1; }
    }

    @-ms-keyframes blink {
      0% { opacity:1; }
      50% { opacity:0; }
      100% { opacity:1; }
    }

    @-o-keyframes blink {
      0% { opacity:1; }
      50% { opacity:0; }
      100% { opacity:1; }
    }
  </style>
</head>

<body>
  <p id="line1" class="hidden">ABCXYZDEF</p>
  <p id="cursor-line" class="visible">&gt;<span class="typed-cursor">_</span></p>

  <script>
    // set typing speed and wait times
    var timeInit = 400;     // initial wait before typing first line
    var timeGap = 1000;      // wait time between each line
    var timeChar = 110;       // time until next letter

    var cursorChar = '_';

    var originId = ['line1'];
    var originText = new Array();
    for (var i = 0; i < originId.length; i++) {
      originText.push(document.getElementById(originId[i]).innerHTML);
    }

    var cursorLine = document.getElementById('cursor-line');

    var currentTimeout;
    var showCursor;

    var typeWriter = function(index) {
      var loc = document.getElementById(originId[index]);
      var fullText = originText[index];
      var letterCount = 0;

      // this function spits out one letter per call, then calls the subsequent typeLetter()
      var typeLetter = function() {
        currentTimeout = setTimeout(function() {
          loc.className = 'visible';
          letterCount += 1;
          var showText = fullText.substring(0, letterCount);

          // stops the function from self-calling when all letters are typed
          if (letterCount === fullText.length) {
            loc.innerHTML = '&gt;' + showText + '<span class="typed-cursor">' + cursorChar + '</spa';
          } else {
            loc.innerHTML = '&gt;' + showText + '<span class="typed-cursor">' + cursorChar + '</span>';
            typeLetter();
          }
        }, timeChar);
      };

      typeLetter();

      // show cursor on next line
    };

    // calculated time delays
    var delayTime = [timeInit];
    var cumulativeDelayTime = [timeInit];
    for (var i = 0; i < originId.length; i++) {
      var elapsedTimeLine = originText[i].length * timeChar + timeGap + timeChar * 2;
      delayTime.push(elapsedTimeLine);
      var sum = 0;
      for (var j = 0; j < delayTime.length; j++) {
        sum += delayTime[j];
      }
      cumulativeDelayTime.push(sum);
    }

    // calls setTimeout for each line
    var typeLineTimeout = new Array();
    for (var i = 0; i < originId.length; i++) {
      typeLineTimeout[i] = setTimeout(
        (function(index) {
          return function() {
            cursorLine.className = 'hidden';
            typeWriter(index);
          };
        })(i),
        cumulativeDelayTime[i]
      );
    }

    // stops all timeouts
    var skip = function() {
      clearTimeout(currentTimeout);
      clearTimeout(showCursor);
      for (var i = 0; i < typeLineTimeout.length; i++) {
        clearTimeout(typeLineTimeout[i]);
      }
    };

    // rewrite text with value stored on page load

    // var rewriteText = function(index) {
    //   var loc = document.getElementById(originId[index]);
    //   loc.innerHTML = '&gt; ' + originText[index];
    //   loc.className = 'visible';
    // };

    // trigger skip and rewrite on pressing enter or spacebar
    window.onkeydown = function(key) {
      if (key.which === 13 || key.which === 32) {
        skip();
        originId.forEach(rewriteText);
        document.getElementById('cursor-line').className = 'visible';
      }
    };
  </script>
</body>
</html>

I tried to add another but the loop works improperly.

People API updateContact method stopped working for updating user defined field

This code has been working perfectly for some time:

  let newUserDefined = { key: "aKey",
                         value: "aValue" };
  let resource = {
    userDefined: [newUserDefined],
    etag: person.etag
  };  

  try{                                   
    People.People.updateContact(resource, person.resourceName, 
                              { updatePersonFields: "userDefined" });       
  }
  catch(e){Logger.log("Error: " + e.message);}

(I haven’t included the full context that determines the key and value data.)

Now it does nothing. It throws no exception, reports no error, but the userDefined field is not added to the contact. I waited a few hours thinking it might be a slow synch on Google’s end, cleared my browser cache, check it on my phone….

Has anyone else seen this?

How can I display image files from input file field using vanilla javascript?

Hi I am trying to build a similar functionality to the Dropzone.js library. My problem is that even it displays the correct number of thumbnails when i submit my form it submits only the last selected items. For example in my code try to select firstly 3 images and then 3 more. It will display 6 thumbnails but in the input files its says: 3 files selected. Is there any way to make it so the input will store all files instead of the last selected?

Here is my code:

document.getElementById("authorGallery").addEventListener("change", function(event) {
  var fileZone = document.querySelector(".filezone");
  
  // Retrieve the previously selected files, if any
  var selectedFiles = Array.from(fileZone.querySelectorAll(".author-gallery-image"));

  var files = event.target.files;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];

    var fileItem = document.createElement("div");
    fileItem.classList.add("author-gallery-image");

    var thumbnail = document.createElement("img");
    thumbnail.classList.add("thumbnail");

    (function(fileItem, thumbnail) {
      var reader = new FileReader();
      reader.onload = function(e) {
        var img = new Image();
        img.onload = function() {
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext("2d");

          canvas.width = 800;
          canvas.height = 800;

          var width = Math.min(img.width, 800);
          var height = Math.min(img.height, 800);
          var x = (img.width - width) / 2;
          var y = (img.height - height) / 2;

          ctx.drawImage(img, x, y, width, height, 0, 0, 800, 800);

          thumbnail.src = canvas.toDataURL("image/jpeg");

          canvas = null;
        };
        img.src = e.target.result;
      };
      reader.readAsDataURL(file);
    })(fileItem, thumbnail);

    fileItem.appendChild(thumbnail);
    fileZone.appendChild(fileItem);

    // Add the newly selected file to the array
    selectedFiles.push(fileItem);
  }

  
  // Append the previously selected files back to the file zone
  for (var j = 0; j < selectedFiles.length; j++) {
    fileZone.appendChild(selectedFiles[j]);
  }
});
.filezone {
  display: flex;
  flex-wrap: wrap;
}

.filezone .author-gallery-image {
  flex-basis: 20%; /* Set the width of each item to occupy 20% of the container */
  box-sizing: border-box; /* Include padding and border in the item's width */
  padding: 5px; /* Add some padding around each item */
}

.author-gallery-image img {
width: 100%;
height: auto;
border-radius: 20px;
object-fit: cover;
border: 3px solid transparent;
cursor:pointer;
transition:all ease-in-out 0.2s; 
}
<div id="galleryImages" class="filezone">
    
</div>





<div id="galleryFile">
<input type="file" id="authorGallery" name="authorgallery[]" multiple>
</div>

How can I set a variable to API data without getting undefined?

I’m trying to set ‘shareUrl’ equal to a hardcoded url interpolated with an id which is returned from an API using fetch in an async function. However, it keeps throwing the error that shareUrl is undefined.

function Recipe() {

  let params = useParams();
  const [details, setDetails] = useState({});
  const [activeTab, setActiveTab] = useState('summary');
  const [borderRadius, setBorderRadius] = useState(15);
  let shareUrl;
  

  const fetchDetails = async () => {
    const data = await fetch(`https://api.spoonacular.com/recipes/${params.name}/information?apiKey=${process.env.REACT_APP_API_KEY}`);
    const detailData = await data.json();
    setDetails(detailData);
    shareUrl = `https://dishlyst.netlify.app/recipe/${details.id}`;
    return shareUrl;
  }
  
  
  useEffect(() => {
    fetchDetails();
  }, [params.name]);
  
  useEffect(() => {
      {window.screen.width < 760 ? setBorderRadius(15) : setBorderRadius(0)}
  }, []);

  // console.log(Object.keys(details), 'details')

  return (
    <DetailWrapper>
        <h2>{details.title}</h2>
        
        <ButtonImageContainer>
          <ShareContainerOuter>
          <img src={details.image} alt={details.title} />
          
            <ShareButtonsContainer>
              <ShareIconContainer>
                <BsShareFill/>
              </ShareIconContainer>
              <PinterestShareBtn borderRadius={borderRadius} shareUrl={shareUrl}/>
              <TwitterShareBtn borderRadius={borderRadius} shareUrl={shareUrl}/>
              <FacebookShareBtn borderRadius={borderRadius} shareUrl={shareUrl}/>
              <LineShareBtn borderRadius={borderRadius} shareUrl={shareUrl}/>
              <LinkedInShareBtn borderRadius={borderRadius} shareUrl={shareUrl}/>
              <WhatsAppShareBtn borderRadius={borderRadius} shareUrl={shareUrl}/>
            </ShareButtonsContainer>
          </ShareContainerOuter>

Typescript Node.js can’t load configuration variables with an async fucntion

Working with Node 16.x and ES2022 on a node project. I need to load variables from a config file asynchronously. Right now what I’m getting is something like this.

import mongoose from 'mongoose'
import * as p from '../config.js' // contains the async function

const config = await p.getParams()
console.log(config) 
// outputs expected object of params e.g 
// { db_url: string, 
// db_user: string, 
// db_pass: string }

const uri = `mongdb+srv://${config.db_user}:${config.db_pass}@${config.db_adress}`
console.log(uri) // Outputs mongdb+srv://undefined:undefined:@undefined
const myDB = mongoose.connect(uri) // node crashes. Fails to connect.

I’ve also tried this by using then like this:

p.getParams().then(
  (config) => {
    console.log(config) // gets the expected object again
    const uri = `mongdb+srv://${config.db_user}:${config.db_pass}@${config.db_adress}`}
    // still get the string of 'undefined'
)

Also, I’d like to ideally only call the async function once in my config, and export the result from there. (config variables are used in a few places, so I’d like to call the async function only one time, store the results, and import them synchronously elsewhere.)

socket io Can’t create connection between my fastapi server with my react app using

I am trying to build an real-time chat app using socket io. I am also new and learning socket io. I am getting this error:

    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: sent 1000 (OK); no close frame received
INFO:     connection closed
ERROR:    Exception in ASGI app

don’t understand why the connection is being closed. here is my fast api code:

sio = socketio.AsyncServer(cors_allowed_origins="*")
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# Mount the static files directory
chat_namespace = "/chat"

@sio.event(namespace=chat_namespace)
async def connect(sid, environ):
    print('Connected:', sid)

@sio.event(namespace=chat_namespace)
async def join_room(sid, data):
    room = data['room']
    await sio.enter_room(sid, room, namespace=chat_namespace)
    print('User joined room:', room)

@sio.event(namespace=chat_namespace)
async def leave_room(sid, data):
    room = data['room']
    await sio.leave_room(sid, room, namespace=chat_namespace)
    print('User left room:', room)

@sio.event(namespace=chat_namespace)
async def message(sid, data):
    room = list(await sio.rooms(sid, namespace=chat_namespace))[1]  # Use [1] to get the second room (index 0 is the default room)
    await sio.emit('message', data, room=room, skip_sid=sid, namespace=chat_namespace)
    print('Message:', data, 'in room:', room)

@sio.event(namespace=chat_namespace)
async def disconnect(sid):
    print('Disconnected:', sid)

sio_app = socketio.ASGIApp(sio, static_files={"/static": "static"})

app.mount("/socket.io", sio_app)

@app.get("/mysc")
async def read_root():
    return {"Hello": "Socket.IO"}

here is my react code:

  useEffect(() => {
        const currentUserID = 'A'; // User A's ID
        const recipientUserID = 'B'; // User B's ID
    
        const roomName = generateRoomName(currentUserID, recipientUserID);
    
        const socket = io('http://localhost:8000/mysc', { path: '/socket.io', transports: ['websocket'] });
    
        // Join the room corresponding to the private conversation
        socket.emit('join_room', { room: roomName });
    
        // Send a private message
        socket.emit('message', { text: 'Hello, user B!' });
    
        // Listen for messages
        socket.on('message', (message) => {
          console.log('Received private message:', message);
        });
    
        // Clean up the WebSocket connection on component unmount
        return () => {
          socket.disconnect();
        };
      }, []);
    
      // Function to generate the room name
      const generateRoomName = (user1, user2) => {
        // Sort the user IDs to ensure consistent room naming
        const sortedIDs = [user1, user2].sort();
        return `${sortedIDs[0]}-${sortedIDs[1]}`;
      };

my react server running on localhost:3000 and fast api running on loaclhost:8000

React application shows blank screen

Below is my App.js :

`

import React from 'react';
import './App.css';
import Register from './Register';
import LandingPage from './LandingPage';
import OrderMedicine from './OrderMedicine';
import Supply from './Supply';
import Track from './Track';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
// import parseCSV from './drugsData';
// import DrugRecommendation from './DrugRecommendation';

function App() {
return (
<div className="App">
<Navbar bg={window.location.pathname === "/" ? "transparent" : "primary"} expand="lg" variant="dark">
<Container>
<Navbar.Brand href="/">
<img height="36" src="https://media.licdn.com/dms/image/C560BAQFNmtBoYNk7fg/company-logo_200_200/0/1582999540395?e=2147483647&v=beta&t=e32Kjj8eEAe6gpjMdtY80-O02ZQV9GsZqKnYjXflHJo" /> WEB 3.0
</Navbar.Brand>
<Navbar.Toggle aria-controls="navbar-nav" />
<Navbar.Collapse id="navbar-nav">
<Nav className="me-auto">
<Nav.Link href="/register" className={window.location.pathname === "/register" ? "active-link" : ""}>Register</Nav.Link>
<Nav.Link href="/order-medicine" className={window.location.pathname === "/order-medicine" ? "active-link" : ""}>Order Medicines</Nav.Link>
<Nav.Link href="/control-supply-chain" className={window.location.pathname === "/control-supply-chain" ? "active-link" : ""}>Control Supply Chain</Nav.Link>
<Nav.Link href="/track-medicine" className={window.location.pathname === "/track-medicine" ? "active-link" : ""}>Track Medicines</Nav.Link>
<Nav.Link href="/drug-recommendation" className={window.location.pathname === "/drug-recommendation" ? "active-link" : ""}>Drug Recommendation</Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
<Router>
<Routes>
<Route path="/" element={<LandingPage/>} />
<Route path="/register" element={<Register/>} />
<Route path="/order-medicine" element={<OrderMedicine/>} />
<Route path="/control-supply-chain" element={<Supply/>} />
<Route path="/track-medicine" element={<Track/>} />
{/* <Route path="/drug-recommendation" element={<DrugRecommendation/>} /> */}
</Routes>
</Router>

    </div>

);
}

export default App;

`

This application is loading. But when I un-comment this line - ({/* <Route path="/drug-recommendation" element={<DrugRecommendation/>} /> */} ) in the Routes section, the app goes blank. No errors are shown so hard to detect what is going wrong.

DrugRecommendation.js

`

import React, { useState, useEffect } from 'react';
import { parseCSV } from './drugsData';
import drugsData from './drugsData'; //Importing the drugs data array

const csvURL = 'file_path_in_my_device';

function DrugRecommendation() {
const [condition, setCondition] = useState('');
const [recommendedDrugs, setRecommendedDrugs] = useState([]);
const [error, setError] = useState('');

    useEffect(() => {
        const fetchData = async () => {
            try {
                //Fetch and parse the CSV data
                const parsedData = await parseCSV(csvURL);
    
                //Filter the drugs based on the selected condition
                const filteredDrugs = parsedData.filter(drug => drug.Condition.toLowerCase().includes(condition.toLowerCase()));
                setRecommendedDrugs(filteredDrugs);
            } catch (error) {
                console.error('Error fetching and parsing CSV:' , error);
            }
        };
    
        fetchData();
    }, [condition]);
    
    const handleInputChange = event => {
        setCondition(event.target.value);
        setError('');
    };
    
    const handleSubmit = event => {
        event.preventDefault();
    
        if (condition.trim() === '') {
            setError('Please enter a condition.');
            setRecommendedDrugs([]);
        } else {
            const filteredDrugs = recommendedDrugs.filter(drug => drug.Condition.toLowerCase().includes(condition.toLowerCase()));
    
            if (filteredDrugs.length === 0) {
                setError(`No drugs found for the condition "${condition}"`);
            }
    
            setRecommendedDrugs(filteredDrugs);
        }
    };
    
    return (
        <div className="drug-recommendation-page">
            <h1>Drug Recommendation</h1>
            <form onSubmit={handleSubmit}>
                <label htmlFor="condition-input">Enter a condition:</label>
                <input 
                    type="text"
                    id="condition-input"
                    value={condition}
                    onChange={handleInputChange}
                    placeholder="Enter condition"
                />
                <button type="submit">Search</button>
            </form>
            {error && <p className="error-message">{error}</p>}
            {recommendedDrugs.length > 0 ? (
                <div className="recommended-drugs">
                    <h3>Recommended Drugs:</h3>
                    <ul>
                        {recommendedDrugs.map(drug => (
                            <li key={drug.DrugName}>
                                {drug.DrugName} (Score: {drug.MeanNormalizedScore})
                            </li>
                        ))}
                    </ul>
                </div>
            ) : (
                !error && <p>No drugs found for the entered condition.</p>
            )}
        </div>
    );

}

export default DrugRecommendation;

`

drugsData.js

`

import { parse } from 'csv-parse';

export const parseCSV = async (csvURL) => {
try {
const response = await fetch(csvURL);
const text = await response.text();
const parsedData = await new Promise((resolve, reject) => {
parse(text, {
columns: true,
skip_empty_lines: true,
}, (err, records) => {
if (err) {
reject (err);
} else {
resolve(records);
}
});
});

    return parsedData;

} catch (error) {
throw new Error('Error fetching and parsing CSV : ' + error.message);
}
};

export default drugsData;

`

webpack.config.js

`

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
// const EslintWebpackPlugin = require("eslint-webpack-plugin");

const extensions = [".js", ".jsx"];

module.exports = {
mode: process.env.NODE_ENV === "production" ? "production" : "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
extensions,
fallback: {
stream: require.resolve("stream-browserify"),
},
},
devServer: {
static: {
directory: path.resolve(__dirname, "dist"),
},
hot: true,
historyApiFallback: true,
client: {
overlay: false,
},
},

module: {
rules: [
{
test: /.js$/i,
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-react", "@babel/preset-env" ],
},
},
],
exclude: /node_modules/,
},
{
test: /.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /.s[ac]ss$/i,
use: ["style-loader", "css-loader", "sass-loader"],
},
{
test: /.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
},
{
test: /.(woff|woff2|eot|ttf|otf)$/i,
type: "asset/resource",
},
],
},

plugins: [
// //     new EslintWebpackPlugin({ extensions }),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "./public/index.html"),
filename: 'index.html'
}),
],
//   stats: "minimal",
};

`

index.js

`

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import "bootstrap/dist/css/bootstrap.min.css";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
{typeof window !== "undefined" && window.location.pathname !== "/" && <footer className="footer">
<div>Developed By : Geetika Raut</div>
</footer>}
</React.StrictMode>
);

`
drugsData.js -- is trying to convert data from a csv file and store it as an array. The csv file contains columns Condition, DrugName, MeanNormalizedScore

DrugRecommendation -- is trying to use the above array to take input a condition from the user and display the drugs associated with that condition.

Kindly help me resolve this issue.

Help me to resolve this issue and load the application and the drug recommendation system to work correctly for this.