Why await stops further execution without throwing error in JavaScript?

Within React hook I have defined async function. That function calls another function and awaits the result. Await call is wrapped in try .. catch .. finally block. For some reason in some cases, when code execution reaches await – it stops.

Code looks more or less like this:

const useCustomHGook = () = {
   const searchMutation = useSearchMutation();

   const onSearch = async (searchParams: ISearchParams) => {
      try {
         // some code
         const resposnse = await searchMutation({params});
         // handling results
      } catch (error) { 
         // some code
      } finally { 
         // some code
      }
   }

   return { onSearch };
}

SearchMutation is another hook which wraps request execution using react-query:

const mutatePromise = async (variables: Variables, options?: IMutationOptions<Data, Error, Variables>) => {
    return new Promise<Data>((resolve, reject) => {
        result.mutate(variables, {
            ...options,
            onSuccess: data => {
                resolve(data);
            },
            onError: error => {
                reject(error);
            },
        });
    });
};

In some specific cases (when multiple calls are executed in short period of time) onSuccess function is resolved with undefined value. In this case onSearch function stops execution of code after awaiting searchMutation function call.

How is it possible? Resolving promise with undefined shouldn’t prevent further code execution after all. Moreover no error is thrown. It just silently stops…

Do you have at least any hints how to debug such issue?

Jquery carousel is not responsive and not scrolling properly

I have created a carousel that should scroll to the left until the last card is shown. The left button is supposed to be hidden until scrolling starts. Once the end of the cards is reached the right button should be hidden. I would also like for it to be responsive. Currently the offset is not working the way it should be

This is the html

<div class="carousel-container">
        <button class="carousel-btn btn-left"><img src="/images/icons/arrow-right.svg"
                alt="Image of right arrow" /></button>
        <button class="carousel-btn btn-right"><img src="/images/icons/arrow-right.svg"
                alt="Image of right arrow" /></button>
        <div class="carousel-ext">
            <div class="carousel-wrapper">
                <div class="carousel-card">
                    <div class="carousel-card-header">
                        <img src="/images/icons/double-quotes.png" alt="Double quotes images" class="double-quotes" />
                    </div>
                    <div class="carousel-card-body">
                        <p>
                            Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugit,
                            labore tempora cumque sapiente tenetur itaque nulla voluptatum,
                            laboriosam ipsa explicabo veniam debitis libero sint similique. Voluptate id dolore officiis ex!
                        </p>
                    </div>
                </div>
                <div class="carousel-card">
                    <div class="carousel-card-header">
                        <img src="/images/icons/double-quotes.png" alt="Double quotes images" class="double-quotes" />
                    </div>
                    <div class="carousel-card-body">
                        <p>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit.
                            Nisi, necessitatibus enim tenetur sequi similique corrupti eum exercitationem aperiam assumenda
                            facilis. Pariatur non assumenda maxime eveniet mollitia delectus voluptatum velit veritatis.
                        </p>
                    </div>
    
                </div>
                <div class="carousel-card">
                    <div class="carousel-card-header">
                        <img src="/images/icons/double-quotes.png" alt="Double quotes images" class="double-quotes" />
                    </div>
                    <div class="carousel-card-body">
                        <p>
                            Lorem ipsum dolor sit amet consectetur adipisicing elit.
                            Voluptate corporis deserunt quaerat, provident repellat reprehenderit nulla? Veniam vel
                            explicabo inventore hic debitis quam consequuntur dicta enim voluptatem deserunt, nobis ut.
                        </p>
                    </div>
                </div>
                <div class="carousel-card">
                    <div class="carousel-card-header">
                        <img src="/images/icons/double-quotes.png" alt="Double quotes images" class="double-quotes" />
                    </div>
                    <div class="carousel-card-body">
                        <p>
                            Lorem ipsum dolor sit amet consectetur, adipisicing elit. At impedit ad soluta accusantium
                            repellendus quos nemo, ducimus omnis? Mollitia, amet? Aut dicta sunt, mollitia tenetur error
                            laboriosam at reprehenderit expedita.
                        </p>
                    </div>
                </div>
                <div class="carousel-card">
                    <div class="carousel-card-header">
                        <img src="/images/icons/double-quotes.png" alt="Double quotes images" class="double-quotes" />
                    </div>
                    <div class="carousel-card-body">
                        <p>
                            Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis, sunt repudiandae.
                            Eum eaque totam sapiente corrupti et, voluptatibus, harum l
                            audantium voluptatem asperiores explicabo, exercitationem hic reiciendis quia quis vel in.
    
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

This is the scss

.carousel-container {
    margin: 78px 0 0 98px;
    position: relative;


    .carousel-btn {
        height: 56px;
        width: 56px;
        background-color: $white;
        position: absolute;
        border: none;
        border-radius: 50%;
        top: 64%;
        z-index: 1;

        &.btn-right {
            right: 70px;
        }

        &.btn-left {
            left: -28px;
            display: none;

            img {
                transform: rotate(180deg);
            }
        }

        &:hover {
            transform: scale(1.2);
        }
    }

    .carousel-ext {
        overflow: hidden;

        .carousel-wrapper {
            display: inline-flex;
            overflow: hidden;
            position: relative;


            .carousel-card {
                width: 294px;
                height: 441px;
                border-radius: 8px;
                padding: 32px;
                display: flex;
                flex-direction: column;
                color: $white;
                margin-right: 8px;

                &.carousel-purple {
                    background-color: $purple-5;
                }

                .carousel-card-header {
                    margin-bottom: 70px;

                    .double-quotes {
                        float: left;
                    }
                }

                .carousel-card-body {
                    flex: 1 1 auto;
                    text-align: left;
                }

                .carousel-card-footer {
                    display: flex;
                    align-items: end;

                    img {
                        height: 54px;
                        width: 54px;
                        border-radius: 50%;
                    }

                    .subheader {
                        @include manrope-subheader;
                    }

                    .opaque-text {
                        opacity: 0.7;
                    }
                }
            }
        }
    }
}

This is the jquery

$(document).ready(function () {
    var cardWidth = $('.carousel-card').outerWidth(true);
    var carouselWidth = $('.carousel-wrapper').outerWidth(true);
    var maxOffset = carouselWidth - cardWidth;
    var cards = $('.carousel-card');
    var colors = ['#6E49BC', '#BF6389', '#129490', '#003857', '#212832'];
    var colorIndex = 0;

 


    //Assign the colors to cards
    cards.each(function () {
        $(this).css('background-color', colors[colorIndex]);
        colorIndex++;
        if (colorIndex == colors.length) {
            colorIndex = 0;
        }
    });


    // Initially hide the left button
    $('.btn-left').hide();

    // Attach click event handler to the right button
    $('.btn-right').click(function () {
        var currentOffset = $('.carousel-wrapper').offset().left;
         console.log("Current offset", currentOffset);
        var newOffset = currentOffset + cardWidth;



        // Show the left button when the right button is clicked and the carousel moves left
        if (newOffset > 0) {
            $('.btn-left').show();
        }

       

        // Hide the right button when the last card is fully shown
        if (newOffset >= maxOffset) {
            newOffset = maxOffset;
            $(this).hide();

            console.log("Hide right  me");
        }
        else {
            console.log("I am not hiding");
        }

        $('.carousel-wrapper').animate({ left: -newOffset }, 500);
    });

    // Attach click event handler to the left button
    $('.btn-left').click(function () {
        var currentOffset = $('.carousel-wrapper').scrollLeft();
        var newOffset = currentOffset - cardWidth;

        // Show the right button when the left button is clicked and the carousel moves right
        if (newOffset < maxOffset) {
            $('.btn-right').show();
        }

        // Hide the left button when the first card is fully shown
        if (newOffset <= 0) {
            newOffset = 0;
            $(this).hide();
        }

        $('.carousel-wrapper').animate({ left: -newOffset }, 500);
    });
});

Glitching Issue with Video Lightbox

I implemented this lightbox into my website:
https://codepen.io/darcyvoutt/pen/MaamWg/

`<div id="container">
  <center>
    <p>Open the lightbox with below button</p>
    <button id="playme" onclick="revealVideo('video','youtube')">Play Video</button>
  </center>
</div>

<div id="video" class="lightbox" onclick="hideVideo('video','youtube')">
  <div class="lightbox-container">  
    <div class="lightbox-content">
  
      <button onclick="hideVideo('video','youtube')" class="lightbox-close">
        Close | ✕
      </button>
      <div class="video-container">
        <iframe id="youtube" width="960" height="540"       src="https://www.youtube.com/embed/WsptdUFthWI?showinfo=0" frameborder="0" allowfullscreen></iframe>
      </div>      
  
    </div>
  </div>
</div>`

However, after the fact I’ve noticed an issue with it:

If you open the lightbox, play the video, close the lightbox, and then open it again, the dimmer part of the lightbox loads in all wonky and in sections.

NOTE: this issue only shows up on desktop, not mobile.

I’ve tried messing with the code but for the life of me can’t fix this issue. Any ideas on how this could be resolved?

Thank you!

Creating a heatmap in Leaflet Js

I am trying to create a Leaflet map using this solution. I pasted the code to my javascript file called heatmap.js which is referenced in a <script> tag of my html file called map.html.

The code I pasted into my heatmap.js is as follows.

var map = L.map('myMap').setView([0.3556, 37.5833], 6.5);

L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

///////////////////////////////////////////////////////
var geoJsonUrl = "https://raw.githubusercontent.com/sammigachuhi/geojson_files/main/selected_hospitals.json";

L.geoJson.ajax(geoJsonUrl, {
    //

    success: function (geoJSON) {
      // Create a heatmap layer and add the GeoJSON data to it
      var heatmapLayer = L.heatLayer(geoJSON.features.map(function (feature) {
        return [feature.geometry.coordinates[1], feature.geometry.coordinates[0]];
      }))
    }
  }).addTo(map);

heatmapLayer.setOptions({
    // Customize heatmap options here, such as radius, gradient, etc.
    radius: 40,
    blur: 10, 
    gradient: {
            '0': 'Navy', '0.25': 'Navy',
            '0.26': 'Green',
            '0.5': 'Green',
            '0.51': 'Yellow',
            '0.75': 'Yellow',
            '0.76': 'Red',
            '1': 'Red'
            }
});

heatmapLayer.addTo(map); // Add the heatmap layer to the map

The purpose is to create a heatmap and the Leaflet.heat plugin is already included in my html file as <script src="my-directoryLeaflet.heat-gh-pagesdistleaflet-heat.js"></script>.

Running the Javascript code only generates the json features as marker points, which are actually hospital locations, however, my main interest is generating a heatmap from the json file.

enter image description here

Running the above code generates this error in the console:

enter image description here

I know variables in local scope cannot be available in global scope, but being clever by even inserting the heatmapLayer.setOptions and heatmapLayer.addTo(map) within the L.geoJson.ajax especially after the success key yields no results.

How can I create a heatmap in leafletjs using L.heatLayer and a json file in a server?

Cannot execute clone on Response – response body already used in service worker for caching

This error only occurs when I try to load google’s material font icons.

Expected behavior: it loads the font icons and caches them for offline use

Actual behavior: it errors out and sends a 408 and gives the title as an error

running in chrome on windows on localhost.

https://pastebin.com/S863bT4w

/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" /> 
/**@type {ServiceWorkerGlobalScope} self */

async function fastget({req}) {
    cache_res = await self.caches.match(req)
    if (cache_res) {
        if (req.url === cache_res.url) {
            return cache_res;
        }
    }

    try {
        network_res = await fetch(req)
        // checks whether to cache or not
    } catch (err) {
        console.error(err)
    }
}

self.addEventListener('install', ev => {
    ev.waitUntil(self.caches.open('basecache').then(cache => {
        cache.addAll(stuff_to_be_cached).then(() => {console.log('Installed!')})
    }))
    ev.waitUntil(self.skipWaiting())
})

self.addEventListener('activate', ev => {
    ev.waitUntil(self.clients.claim())
})

self.addEventListener('fetch', ev => {
    ev.respondWith(fastget({
        req: ev.request
    }))
})

error

Cloudfront.net Main Thread Blocking Time?

My web app uses cloudfront.net as a CDN. Google Lighthouse is saying it adds 598ms to my main-thread blocking time:

enter image description here

Does Lighthouse mean that cloudfront.net could be accessed in a non-render-blocking way? Or is it just saying that other components of my web app, which are being loaded via the CDN, need to be addressed separately to reduce the blocking time that those individual components contribute?

Use keyframes to change the width of an SVG while keeping it static on the page

I am attempting to animate an SVG. In the example below, the pink square moves 50px to the right. I am attempting to make the orange rectangle’s right side grow to match the location of the pink square (so they are flush), while keeping the rest of the orange square static.

The animation currently goes for two seconds (two full cycles) when the button is pressed. I have attempted to use scale() and translate(). From my understanding:

  • scale() is designed to change the size of the shape equally.
  • translate() is designed to move the entire shape around on the page.

I have also attempted to change the width of the orange rectangle, but I believe that this is incorrect because that property is not a transform property.

Thanks!

function startAnimation(time) {
  document.getElementById("pink").style.animation =
    "slide 1s ease forwards infinite";
  document.getElementById("orange").style.animation = "grow 1s ease forwards infinite";

  setTimeout(function() {
    document.getElementById("pink").style.animation = "";
    document.getElementById("orange").style.animation = "";
  }, time);
}
body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0;
  padding: 0;
  min-height: 100vh;
}

#svg5 {
  width: 75vh;
  height: auto;
}

#pink,
#orange {
  animation-delay: 0.1s;
}

@keyframes slide {
  0% {
    transform: translate(none);
  }
  50% {
    transform: translate(50px);
  }
  100% {
    transform: translate(none);
  }
}

@keyframes grow {
  0% {
    /* ? */
  }
  50% {
    /* ? */
  }
  100% {
    /* ? */
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>SVG Grow</title>
</head>

<body>
  <svg viewBox="0 0 200 200" version="1.1" id="svg5" xmlns="http://www.w3.org/2000/svg"><g id="canvas" transform="translate(5 -165)"><g id="pink"><path id="pink-box" fill="#ff00e2" fill-opacity="1" stroke-width=".214" d="M105 255h20v20h-20z"/></g><g id="orange"><path id="orange-box" fill="#ff9300" stroke-width=".755" d="M65 257h40v15H65z"/></g></g></svg>
  </svg>

  <button id="animation" onClick={startAnimation(2000)}>Animate!</button>

</body>

</html>

How do I query within “ element?

What am I doing wrong here? Why am I not able to select the link within the template?

Found 3 template(s)
Found 0 link(s)
Found 0 link(s)
Found 0 link(s)

const templates = [...document.getElementsByTagName('template') || []]
console.log(`Found ${templates.length} template(s)`)

templates.map((template) => {
  const links = [...template.getElementsByTagName('link') || []]
  console.log(`Found ${links.length} link(s)`)
})
Example HTML:
<template></template>
<template>
  <link/>
</template>
<template></template>

how to shrink spaces in text editor when using ?

I copy and paste this paragraph into my text editor …
enter image description here

then I apply css “justify-content: space-around;” and this happens:
enter image description here

The spaces between the words with “b” tags and the words without are bigger than the other ones, tried with justify-content:space-evenly and justify-content:center and I get the same results.
My text editor have this properties:

  • font: Times New Roman
  • font-size: 17px

How can I make angular material chart interactive?

I’m developing a chart with Angular Materials using this guide here:

https://c-sharpcorner.com/articles/how-to-add-charts-in-angular-material-components/

I would like to go further than this article takes me by making the charts interactive. That is, I would like the user to be able to select individual data points and regions of data points. Something like this:

https://lightningchart.com/lightning-chart-js-interactive-examples/edit/lcjs-example-0040-customLassoInteraction.html?isList=true

Is this possible with Angular materials?

Not a number occurs when adding or subtracting points from saved houses

I have this HTML script with some JavaScript code for a school project that will receive a house id and how many points a house has (kind of like Harry Potter). The data is being pulled from a few text files by a Flask python script rendering the HTML sites. The data gets over okay, but I want the houses and their points to display when the site loads, and that works, but if I add or remove points, it says NaN. I’ve been working with ChatGPT, but its not really working. Here is my HTML script (sorry its kind of long):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        .header-container {
            text-align: center;
        }

        .button-container {
            margin-bottom: 20px;
            text-align: center;
        }

        .house-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .house {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 10px;
            padding: 10px;
            border: 1px solid #000000;
            border-radius: 4px;
            background-color: #ffffff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .house-icon {
            width: 100px;
            height: 100px;
            margin-bottom: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid #000000;
            border-radius: 50%;
            background-color: #000000;
        }

        .circle {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background-color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
        }


        .inner-circle {
            font-size: 24px;
            font-weight: bold;
            color: #000000;
        }

        .house-name {
            font-weight: bold;
            text-align: center;
            margin-bottom: 5px;
        }

        .button-container-house {
            display: flex;
            justify-content: space-between;
        }

        .button {
            padding: 5px 10px;
            font-size: 14px;
            font-weight: bold;
        }

        .submit-button {
            background-color: #4caf50;
            color: #fff;
        }

        .cancel-button {
            background-color: #f44336;
            color: #fff;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fff;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
        }

        .close-button {
            color: #888;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .textbox-container {
            margin-bottom: 10px;
        }

        .textbox {
            width: 100%;
            padding: 5px;
            font-size: 14px;
        }

        .blue-number {
            color: blue;
        }
    </style>
</head>
<body>
    <div class="header-container">
        <h1>Teacher's Dashboard</h1>
    </div>

    <div class="button-container">
        <button class="button" onclick="createHouse()">Create House</button>
    </div>

    <div class="house-container" id="houses">
        {% for house_id, points in house_points.items() %}
        <div class="house" id="{{ house_id }}">
            <div class="house-name">{{ house_id }}</div>
            <div class="house-icon">
                <div class="circle">
                    <span class="inner-circle">{{ points }}</span>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    <div id="modal" class="modal">
        <div class="modal-content">
            <span class="close-button" onclick="closeModal()">&times;</span>
            <div class="house-name" id="houseName"></div>
            <div class="house-icon">
                <div class="circle">
                    <span class="inner-circle"></span>
                </div>
            </div>
            <div class="button-container-house">
                <button class="button" onclick="addPoints(1)" data-houseid="{{ house_id }}">+1</button>
                <button class="button" onclick="subtractPoints(1)" data-houseid="{{ house_id }}">-1</button>
                <button class="button" onclick="addPoints(5)" data-houseid="{{ house_id }}">+5</button>
                <button class="button" onclick="subtractPoints(5)" data-houseid="{{ house_id }}">-5</button>
            </div>
            <div class="textbox-container">
                <input type="text" class="textbox" placeholder="Reason">
            </div>            
            <div class="button-container-house">
                <button class="button submit-button" onclick="submitPoints()">Submit</button>
                <button class="button cancel-button" onclick="cancelPoints()">Cancel</button>
                <button class="button remove-button" onclick="removeHouse()">Remove</button>
            </div>
            <div id="outerNumber"></div>
        </div>
    </div>
    <script>
        var savedPoints = {}
        var unsavedPoints = {};

        // Function to send data to Flask via a POST request
        function sendData(url, data) {
            fetch(url, {
                method: 'POST',
                body: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (response.ok) {
                    // Handle successful response
                    console.log('Data sent successfully');
                } else {
                    // Handle error response
                    console.error('Failed to send data:', response.status);
                }
            })
            .catch(error => {
                // Handle fetch error
                console.error('Error sending data:', error);
            });
        }

        function createHouse() {
            var houseName = prompt("Enter the name for the new house:");
            if (houseName) {
                var houseId = houseName.replace(/s+/g, "-").toLowerCase();
                savedPoints[houseId] = 0;
                unsavedPoints[houseId] = 0;

                var houseContainer = document.getElementById("houses");

                var houseDiv = document.createElement("div");
                houseDiv.id = houseId;
                houseDiv.classList.add("house");

                var houseNameDiv = document.createElement("div");
                houseNameDiv.classList.add("house-name");
                houseNameDiv.textContent = houseName;
                houseDiv.appendChild(houseNameDiv);

                var houseIconDiv = document.createElement("div");
                houseIconDiv.classList.add("house-icon");

                var circleDiv = document.createElement("div");
                circleDiv.classList.add("circle");

                var innerCircleSpan = document.createElement("span");
                innerCircleSpan.classList.add("inner-circle");
                innerCircleSpan.textContent = savedPoints[houseId];

                circleDiv.appendChild(innerCircleSpan);
                houseIconDiv.appendChild(circleDiv);
                houseDiv.appendChild(houseIconDiv);

                houseDiv.addEventListener("click", function() {
                    openModal(houseId);
                });

                houseContainer.appendChild(houseDiv);

                sendData('/create_house', { 'house_id': houseId });
            }
        }

        function openModal(houseId) {
            console.log('Open Modal:', houseId, savedPoints, unsavedPoints);

            var modal = document.getElementById("modal");
            var houseName = document.getElementById("houseName");
            var innerCircle = document.querySelector("#modal .inner-circle");
            var textbox = document.querySelector("#modal .textbox");

            houseName.textContent = houseId;
            modal.dataset.houseId = houseId;

            if (unsavedPoints.hasOwnProperty(houseId)) {
                var unsavedPointsValue = parseInt(unsavedPoints[houseId]);
                console.log("Unsaved Points:", unsavedPointsValue);
                innerCircle.textContent = unsavedPointsValue;
            } else if (savedPoints.hasOwnProperty(houseId)) {
                var savedPointsValue = parseInt(savedPoints[houseId].points);
                console.log("Saved Points:", savedPointsValue);
                innerCircle.textContent = savedPointsValue;
            } else {
                innerCircle.textContent = "";
            }

            textbox.value = "";

            modal.style.display = "block";
        }

        function closeModal() {
            var modal = document.getElementById("modal");
            modal.style.display = "none";
        }

        function addPoints(value) {
            var modal = document.getElementById("modal");
            var houseId = modal.dataset.houseId;
            var innerCircle = document.querySelector("#modal .inner-circle");
            var points = unsavedPoints.hasOwnProperty(houseId) ? unsavedPoints[houseId] : savedPoints[houseId];
            points = parseInt(points) + value;
            unsavedPoints[houseId] = points;
            innerCircle.textContent = points.toString();
        }

        function subtractPoints(value) {
            var modal = document.getElementById("modal");
            var houseId = modal.dataset.houseId;
            var innerCircle = document.querySelector("#modal .inner-circle");
            var points = unsavedPoints.hasOwnProperty(houseId) ? unsavedPoints[houseId] : savedPoints[houseId];
            points = parseInt(points) - value;
            unsavedPoints[houseId] = points;
            innerCircle.textContent = points.toString();
        }

        function cancelPoints() {
            var modal = document.getElementById("modal");
            var houseId = modal.dataset.houseId;
            var innerCircle = document.querySelector("#modal .inner-circle");
            var points = savedPoints[houseId];
            delete unsavedPoints[houseId];
            innerCircle.textContent = parseInt(points, 10);
            closeModal();
        }

        function submitPoints() {
            var modal = document.getElementById("modal");
            var houseId = modal.dataset.houseId;

            var data = {
                house_id: houseId,
                points: Number(unsavedPoints[houseId] || savedPoints[houseId]),
                reason: document.querySelector("#modal .textbox").value
            };

            sendData('/save_house_points', data);
            closeModal();
        }

        function fetchHousePoints() {
            fetch('/get_house_points')
                .then(response => response.json())
                .then(data => {
                    console.log('Fetched Data:', data);

                    savedPoints = data;
                    unsavedPoints = {}; // Reset unsavedPoints

                    var houseContainer = document.getElementById('houses');
                    houseContainer.innerHTML = '';

                    Object.keys(data).forEach((houseId, index) => {
                        var points = parseInt(data[houseId].points);

                        var houseDiv = document.createElement('div');
                        houseDiv.id = houseId;
                        houseDiv.classList.add('house');

                        var houseNameDiv = document.createElement('div');
                        houseNameDiv.classList.add('house-name');
                        houseNameDiv.textContent = houseId;
                        houseDiv.appendChild(houseNameDiv);

                        var houseIconDiv = document.createElement('div');
                        houseIconDiv.classList.add('house-icon');

                        var circleDiv = document.createElement('div');
                        circleDiv.classList.add('circle');

                        var innerCircleSpan = document.createElement('span');
                        innerCircleSpan.classList.add('inner-circle');
                        innerCircleSpan.textContent = points.toString();

                        circleDiv.appendChild(innerCircleSpan);
                        houseIconDiv.appendChild(circleDiv);
                        houseDiv.appendChild(houseIconDiv);

                        houseDiv.addEventListener('click', function () {
                            openModal(houseId);
                        });

                        houseContainer.appendChild(houseDiv);
                    });
                })
                .catch(error => {
                    console.error('Error fetching house points:', error);
                });
        }

            window.addEventListener('load', fetchHousePoints);



        function removeHouse() {
            if (confirm("Are you sure you want to remove this house?")) {
                var modal = document.getElementById("modal");
                var houseId = modal.dataset.houseId;

                var formData = new FormData();
                formData.append('houseId', houseId);

                fetch('/remove_house', {
                    method: 'POST',
                    body: formData
                }).then(response => {
                    if (response.ok) {
                        var house = document.getElementById(houseId).parentNode.parentNode;
                        house.parentNode.removeChild(house);
                        delete savedPoints[houseId];
                        delete unsavedPoints[houseId];
                        closeModal();
                        console.log('House removed successfully');
                    } else {
                        console.error('Failed to remove house:', response.status);
                    }
                }).catch(error => {
                    console.error('Error removing house:', error);
                });
            }
            closeModal();
        }

        function updateHousePoints() {
            var houseContainer = document.getElementById("houses");
            houseContainer.innerHTML = ""; // Clear the container

            Object.entries(savedPoints).forEach(function ([houseId, points]) {
                var houseDiv = document.createElement("div");
                houseDiv.id = houseId;
                houseDiv.classList.add("house");

                var houseNameDiv = document.createElement("div");
                houseNameDiv.classList.add("house-name");
                houseNameDiv.textContent = houseId;
                houseDiv.appendChild(houseNameDiv);

                var houseIconDiv = document.createElement("div");
                houseIconDiv.classList.add("house-icon");

                var circleDiv = document.createElement("div");
                circleDiv.classList.add("circle");

                var innerCircleSpan = document.createElement("span");
                innerCircleSpan.classList.add("inner-circle");
                innerCircleSpan.textContent = parseInt(points, 10);

                circleDiv.appendChild(innerCircleSpan);
                houseIconDiv.appendChild(circleDiv);
                houseDiv.appendChild(houseIconDiv);

                houseDiv.addEventListener("click", function () {
                openModal(houseId);
                });

                houseContainer.appendChild(houseDiv);
            });
            }

        // Fetch house points and update the page on load
        window.addEventListener('load', function () {
            fetchHousePoints();
        })
    </script>
</body>
</html>

I was expecting to be able to be able to add and subtract points from the saved houses without error.

How can I pass a variable into a JavaScript function to format a date extracted from a web page?

  1. How to pass a variable into a function in javascript
  2. How to pass result from function back into script

I am a total beginner in javascript and have been using the Automa Extension to do some incredible automation in Chrome, however there are times in which actual scripting is needed.

Let’s say I extract a date from a web page as “Jan 11, 1977” and pass it to the variable $date.

function getDateFormatted(inputdate) {
  var k = inputdate;
  var dt = new Date(k);
  var yr = dt.getYear() + 1900;
  var mn = dt.getMonth() + 1;
  return mn + "/" + dt.getDate() + "/" + yr
}
alert(getDateFormatted("Jan 11, 1977")); ==> 1/11/1997

I’ve tried alert(getDateFormatted($date)) and alert(getDateFormatted({{variables.$date}})) unsuccessfully.

Should I succeed, how do I then pass the result (1/11/1997) back into the script, ie enter it into a form on the webpage?

Awaiting database drop, then closing connection gives MongoExpiredSessionError

I am using Jest to run tests. I use the afterAll() function to drop the database, then closing the connection. However, I am receiving a “MongoExpiredSessionError”.

Relevant code:

afterAll(async ()=>{
    await mongoose.connection.db.dropDatabase((err)=>{console.error(err)});
    mongoose.disconnect();
});

Error:

MongoExpiredSessionError: Cannot use a session that has ended
        at applySession (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/sessions.ts:978:12)
        at Connection.command (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection.ts:519:31)
        at /home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/sdam/server.ts:365:14
        at Object.callback (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection_pool.ts:513:7)
        at ConnectionPool.processWaitQueue (/home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection_pool.ts:689:25)
        at /home/leemorgan/projects/js/api-easycv-work/node_modules/mongodb/src/cmap/connection_pool.ts:357:33
        at processTicksAndRejections (node:internal/process/task_queues:77:11) {
      [Symbol(errorLabels)]: Set(0) {}
    }

It seems to me that disconnect should not run until the database is dropped because I am awaiting. Why is this happening and how do I fix it?

How to prevent a hover component from distorting its parent component in React?

I have a component that is shown on hover. I’m using it inside another component that has some text content. When the hover component is shown, it distorts (pushes) the contents of the component it is used in. Basically, I want to stop the hover component from interfering with its parent component. Here is my code:

LanguageOptions (hover component) styling:

import styled from 'styled-components';

export const LanguagesWrapper = styled.div`
  // removed padding: 0.3rem;
  background-color: #b0b2b7;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  flex-grow: 1; /* Add flex-grow property to expand vertically */
  gap: 0.8rem;
`;

export const StyledLanguagesTitle = styled.p`
  padding: 0.3rem; // added padding here;
  font-size: ${({theme}) => theme.typography.fontSize.medium};
  cursor: pointer;
  transition: background-color 0.3s;
  &:hover {
    background-color: #526d82;
  }
`;

export const ButtonForReferenceLink = styled.button<{
  icon: string;
}>`
  position: relative;
  width: 1.3rem;
  height: 1.3rem;
  background-image: url(${({icon}) => icon});
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  background-color: transparent;
  border: none;
  cursor: pointer;
  :first-of-type {
    height: 1.1rem;
  }
`;

References styling:

import styled, { css } from 'styled-components';


export const StyledWrapper = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  min-width: 200px;
  width: 98%;
  margin: auto;
  padding: 0 5px 0 5px;
  gap: 0.5rem;
`;

export const StyledTitle = styled.h2<{type: boolean}>`
  font-size: ${({theme}) => theme.typography.fontSize.mediumLarge};
  margin-bottom: 1rem;
  color: ${({theme, type}) => (type ? '#e0e0e0' : theme.colors.blue)};
`;

export const StyledInnerWrapper = styled.div<{type: boolean}>`
  width: 100%;
  max-height: 30rem;
  padding-right: 1.3rem;
  overflow-y: scroll;
  margin-bottom: 1rem;
  /* Custom scrollbar styles */
  ::-webkit-scrollbar {
    width: 10px;
    background-color: rgba(
      0,
      0,
      0,
      0.2
    ); /* Add a little bit of opaq gray to the scrollbar background */
  }

  ::-webkit-scrollbar-thumb {
    background-color: ${({type}) =>
      type
        ? '#ff6363'
        : '#779199'}; /* Set the color of the scrollbar bar to red */
    border-radius: 5px;
  }

  ::-webkit-scrollbar-thumb:hover {
    background-color: #c70000; /* Change the color of the scrollbar bar when hovering over it */
  }
`;

export const ReferenceItem = styled.div<{darkMode: boolean}>`
  display: flex;
  background-color: ${({theme, darkMode}) =>
    darkMode ? 'grey' : theme.colors.blueWithOpacity};
  padding: ${({theme}) => theme.spacing.small};
  border-radius: 0.6rem;
  width: 100%;
  height: fit-content;
  margin-bottom: 0.5rem;
  gap: 1rem;
  
`;

export const Content = styled.div`
  width: 100%;
  padding-left: 0.3rem;
  
`;

export const ButtonsWrapper = styled.div`
  display: flex;
  justify-content: start;
  flex-direction: column;
  min-height: 3rem;
  height: 100%;
  padding: 0.3rem;
  gap: 0.8rem;
`;

export const StyledText = styled.p<{small?: boolean, darkMode:boolean}>`

  font-size: ${({theme, small}) =>
    small
      ? theme.typography.fontSize.small
      : theme.typography.fontSize.mediumSmall};

  ${({small}) =>
    small &&
    css`
      font-style: italic;
      padding-top: 0.5rem;
      padding-bottom: 0.4rem;
    `}

  ${({theme}) => theme.breakpoints.up('sm')} {
    font-size: ${({theme, small}) =>
      small
        ? theme.typography.fontSize.small
        : theme.typography.fontSize.medium};
  }
  color: ${({theme, darkMode}) =>
   darkMode ? 'white'  : 'black' }; /* Add the desired color value here */
`;

export const ButtonForReferenceLink = styled.button<{icon: string}>`
  position: relative;
  width: 1.3rem;
  height: 1.3rem;
  background-image: url(${({icon}) => icon});
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  background-color: transparent;
  border: none;
  cursor: pointer;

  :first-of-type {
    height: 1.1rem;
  }
`;

Gif:enter image description here

I tried some CSS on it but couldn’t figure it out.

How to create Black Border for Every Y Scale’s X Axis with Line Chart in Chartjs

Line Chart

I want to have black border in every border of X axises of Y scales.
How can I do it and have a border that starts with 0 in x axises.
So I want to have black border for every x axis and that borders should have value 0.
(I just shared y1 and y2, but there is actually y3 and y4 too in my code)
Here is my code of my scales:

            scales: {
                x: {
                    type: "linear",
                    position: "left",
                    max: this.res.maxs[0],
                    min: 0,
                    gridLines: {
                        display: true,
                    },
                },

                y1: {
                    type: "linear",
                    position: "left",
                    stack: "demo",
                    stackWeight: 1,
                    max: this.res.maxs[4],
                    min: 0,
                    title: {
                        display: true,
                        text: this.axisLabels[3],
                        font: {
                            size: 11,
                        },
                    },
                },
                y2: {
                    type: "linear",
                    position: "left",
                    stack: "demo",
                    stackWeight: 1,
                    grid: {
                        borderColor: "blue",
                    },
                    max: this.res.maxs[2],
                    min: -10,
                    title: {
                        display: true,
                        text: this.axisLabels[1],
                        font: {
                            size: 11,
                        },
                    },
                    ticks: {
                        callback: (value, index, values) =>
                            index == 0 ? undefined : value.toFixed(1),
                    },
                },

               
            }