javascript to fetch the hit count not working in jekyll

I’m not a developer and using jekyll for blog hosting.
I’ve a website aquibqureshi26.github.io and I’m trying to build blog hit tracker on the page to show how many users has visited.
I’ve an API hosted outside, when I’m calling the API via the javascript then it just shows loading… and doesn’t fetch the actual page views.

My API provides output in JSON in below format.

{
  "page": "/my-postnew",
  "hits": 11
}

I’ve modified the _layout and edited the post.html and default.html

Snippet from post.html

   <span>
        <em id="pv" class="pageviews">
          <i class="fa-duotone fa-circle-dot"></i>
        </em>
        <span id="hitCount">Loading...</span>
    </span>
    

Snippet from default.html

<!doctype html>

{% include origin-type.html %}

{% include lang.html %}

{% if site.theme_mode %}
  {% capture prefer_mode %}data-mode="{{ site.theme_mode }}"{% endcapture %}
{% endif %}

<!-- `site.alt_lang` can specify a language different from the UI -->
<html lang="{{ site.alt_lang | default: site.lang }}" {{ prefer_mode }}>
  {% include head.html %}

  <body>
    {% include sidebar.html lang=lang %}

    <div id="main-wrapper" class="d-flex justify-content-center">
      <div class="container d-flex flex-column px-xxl-5">
        {% include topbar.html lang=lang %}

        <div class="row flex-grow-1">
          <main aria-label="Main Content" class="col-12 col-lg-11 col-xl-9 px-md-4">
            {% if layout.refactor or layout.layout == 'default' %}
              {% include refactor-content.html content=content lang=lang %}
            {% else %}
              {{ content }}
            {% endif %}
          </main>

          <!-- panel -->
          <aside aria-label="Panel" id="panel-wrapper" class="col-xl-3 ps-2 mb-5 text-muted">
            <div class="access">
              {% include_cached update-list.html lang=lang %}
              {% include_cached trending-tags.html lang=lang %}
            </div>

            {% for _include in layout.panel_includes %}
              {% assign _include_path = _include | append: '.html' %}
              {% include {{ _include_path }} lang=lang %}
            {% endfor %}
          </aside>
        </div>

        <div class="row">
          <!-- tail -->
          <div id="tail-wrapper" class="col-12 col-lg-11 col-xl-9 px-md-4">
            {% for _include in layout.tail_includes %}
              {% assign _include_path = _include | append: '.html' %}
              {% include {{ _include_path }} lang=lang %}
            {% endfor %}

            {% include_cached footer.html lang=lang %}
          </div>
        </div>

        {% include_cached search-results.html lang=lang %}
      </div>

      <aside aria-label="Scroll to Top">
        <button id="back-to-top" type="button" class="btn btn-lg btn-box-shadow">
          <i class="fas fa-angle-up"></i>
        </button>
      </aside>
    </div>

    <div id="mask"></div>

    {% if site.pwa.enabled %}
      {% include_cached notification.html lang=lang %}
    {% endif %}


        
    <script>
    document.addEventListener("DOMContentLoaded", function () {
    let pageUrl = encodeURIComponent(window.location.pathname);
    let apiUrl = `https://xyz.centralindia-01.azurewebsites.net/api/HttpTrigger1?website=websitename&page=${pageUrl}`;

    console.log("Fetching hit count...");
    console.log("Page URL:", window.location.pathname);
    console.log("Encoded Page URL:", pageUrl);
    console.log("API URL:", apiUrl);

    fetch(apiUrl)
        .then(response => {
            console.log("Raw response:", response);
            return response.text();  // Read as text first
        })
        .then(text => {
            console.log("Raw response text:", text);
            try {
                let data = JSON.parse(text);  // Convert to JSON
                console.log("Parsed JSON data:");
                console.table(data); // Display as a table if it's an object or an array

                if (data.hits) {
                    document.getElementById("hitCount").innerText = `Views: ${data.hits}`;
                } else {
                    document.getElementById("hitCount").innerText = "Views: 0";
                }
            } catch (error) {
                console.error("JSON parsing error:", error);
                document.getElementById("hitCount").innerText = "Views: Error";
            }
        })
        .catch(error => {
            console.error("Error fetching hit count:", error);
            document.getElementById("hitCount").innerText = "Views: N/A";
        });
     });
  </script>
    <!-- JavaScripts -->


    {% include js-selector.html %}

    {% if page.mermaid %}
      {% include mermaid.html %}
    {% endif %}

    {% include_cached search-loader.html %}
  </body>
</html>

when i goto the console, it just shows. I’m unable to debug the javasccript which is under script

Uncaught SyntaxError: Unexpected end of input

any input or direction would help. thanks in advance

How to Implement Drag & Drop in a React Native Masonry List?

I’m looking for a way to implement drag & drop in a Masonry-style list in React Native while also persisting the new order. Most solutions seem to be optimized for FlatList, and I’m struggling to find the right approach for a Masonry layout.

Has anyone done this before or come across useful resources? Any recommendations would be greatly appreciated!

Thanks!

How to navigate to a new page in Material UI Toolpad and change its toolbar in React?

I have a React app that uses the Material UI Toolpad Dashboard layout. The left navigation bar contains the main navigation pages. Those work correctly. There are other pages that I want to navigate to using a Select dropdown in the PageLayout toolbar. That doesn’t work.

I created a sandbox that shows what I mean. You’ll see two icons on the left panel. Default is Home. You’ll see a Select box in the toolbar. I don’t want that toolbar to show when on the home page, only the others.

If you click the human icon, it will go to the Physiology page. If you click the dropdown, you’ll see two options, Physiology and Anatomy. If you select Anatomy, the PageContainer toolbar with the page title and breadcrumbs is gone, and it has not navigated to the Anatomy page.

I’ve wasted so much time on this I’ve finally given up and am asking you experts for help!

How to Resize a GIF While Preserving Animation in React (Client-Side Only)

I am working on a React project where I need to crop, rotate, zoom, and resize images, including animated GIFs.

I am using react-easy-crop for cropping and the Canvas API to generate the final output. This approach works well for static images (JPEG, PNG), but I am facing an issue with resizing animated GIFs:

Issue:
When I resize a GIF using the Canvas API, only the first frame is rendered in the output, and the animation is lost.

What I Have Tried:
Extracting frames using CanvasRenderingContext2D.drawImage(), but it only captures one frame.

Looking into JavaScript-based GIF processing libraries, but many require server-side processing or WebAssembly, which I want to avoid.

I referred to this example, but it does not handle GIF animations correctly.

What I Need Help With:

1️⃣ How can I extract, resize, and reconstruct all frames of an animated GIF on the client-side in JavaScript/React?

2️⃣ Is there a way to process GIFs efficiently without losing animation using the Canvas API or another browser-friendly approach?

I am looking for a technical explanation or code-based approach to solving this problem rather than just library recommendations. Any insights would be greatly appreciated!

Remove Leading 0s from Date Formatted mm/dd/yyyy

I have a date formatted like such:

04/09/2024 10:45

I am trying to remove leading zeros when they exist in the month and day. I have been trying to do this with regex but am struggling to get the outcome I want

dateString = dateString.replace(/0*//g, '')

Can someone point me in the right direction or if there is a simpler way to do this please let me know!

Modify HTML with JavaScript on page load

I’m in the earliest stages of building a website. I’d like to have a consistent navigation bar across all pages on my website, so my plan is to create a navigation bar in its own HTML file and then load it into a div made for it in each page.

At this stage, though, I can’t even seem to get my JavaScript to run. Initially I tried just having the script on its own. With this, neither the modified innerHTML nor the pop-up for testing appear.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="nav-bar">The navigation bar has failed to load.</div>
        <script>
            document.getElementByID("nav-bar").innerHTML="test";
            alert("Hello")
        </script>
        <h1>Welcome</h1>
        <p>This site is under construction.</p>
    </body>
</html>

I also tried using an onload event, but still nothing happened.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div id="nav-bar" onload="load-nav-bar()">The navigation bar has failed to load.</div>
        <script>
            function load-nav-bar(){
                document.getElementByID("nav-bar").innerHTML="test";
                alert("Hello")
            }
        </script>
        <h1>Welcome</h1>
        <p>This site is under construction.</p>
    </body>
</html>

I assume the problem is something with how I’m using JavaScript, but it’s been the better part of a decade since I last used it and if there’s something I’m doing wrong, unfortunately I don’t remember and haven’t been able to figure it out. Can anyone help explain why the JavaScript won’t run?

Svelte input blur triggered when element is focused

Maybe its not related to svelte, but if do some DOM changes after input is focused, for example

<input onfocus={() => toggleVisibiltyOfOtherElement = true } onblur={() => console.log("blur")} />

(toggleVisibiltyOfOtherElement triggers dom changes)

then blur is also triggered. Which doesn’t make any sense, since visually the input is still focused. This makes it impossible to show another element only when input is focused, because showing that element unfocuses the input

Any way to fix this?

Deploying Firebase user().onCreate() Function, undefined ‘user’ error [duplicate]

This is my index.js file:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.createUser = functions.auth.user().onCreate((user) => {
    console.log('user')
})

Whenever, I try to run it in a firebase emulator or deploy it, I get this error message:

TypeError: Cannot read properties of undefined (reading 'user')
    at Object.<anonymous> (C:UserscwrigDesktopgen_mc_skinsfront-end-mc-skinsfunctionsindex.js:7:37)
    at Module._compile (node:internal/modules/cjs/loader:1554:14)
    at Object..js (node:internal/modules/cjs/loader:1706:10)
    at Module.load (node:internal/modules/cjs/loader:1289:32)
    at Function._load (node:internal/modules/cjs/loader:1108:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
    at Module.require (node:internal/modules/cjs/loader:1311:12)
    at require (node:internal/modules/helpers:136:16)
    at loadModule (C:UserscwrigDesktopgen_mc_skinsfront-end-mc-skinsfunctionsnode_modulesfirebase-functionslibruntimeloader.js:40:16)

Furthermore, when I am trying to develop the function and i type functions. I do not see auth popup in ide to autofill.

I have been researching for a few hours, and cannot see what I am missing. I made sure I am on node version 22. I am on firebase tools version: 13.35.1

I have deleted and recreated the firebase functions directory.

I am sure it might just be something small, but nothing I do is fixing it, and documentation seems a little bit out of date to me

change span content m365-chat-editor-target-element javascript

i’m tring to write via a chrome extension text in the input vox of copilot.

I can read the original text “original text”. However, when I try to change it, I don’t get an error, but it doesn’t refresh on the page. If I read it again, it still has the same old value.

I have try this in the console

'original text​‌'
document.querySelector("#m365-chat-editor-target-element").innerText = "New text";
'New text'
document.querySelector("#m365-chat-editor-target-element").innerText
'original text​‌'```

Drag and Drop files upload the Request.Files.Count is zeor

The javascript for drag and drop files can show the file information but when I save the file on the server on vb.net, I get Request.Files.Count is zero. Also I saw error on debug in VS
Upload failed: TypeError: Failed to fetch
at UniversalFileUploader.uploadFilesToServer (C:WebApplication1Default.aspx:167:17)
at HTMLInputElement. (https://localhost:44388/Default.aspx:120:26) {stack: ‘TypeError: Failed to fetch
at UniversalFi…(https://localhost:44388/Default.aspx:120:26)’, message: ‘Failed to fetch’}

I think it is fetch issue. Would someone have idea?

The javascript class constructor:

constructor(options = {}) {
 this.config = {
     dropZoneSelector: options.dropZoneSelector || '#file-drop-zone',
     allowedTypes: options.allowedTypes || ['*'],
     maxFileSize: options.maxFileSize || 50 * 1024 * 1024, // 50MB
     maxFiles: options.maxFiles || 5,
     maxTotalSize: options.maxTotalSize || 100 * 1024 * 1024, // 100MB total
     uploadUrl: options.uploadUrl || 'Default.aspx' // Ensure correct upload URL
 };

 this.uploadedFiles = [];
 this.init();
}

The javascript for fetch in my javascript class

uploadFilesToServer(filesArray) {
            const formData = new FormData();

            filesArray.forEach(file => {
                formData.append("files", file);
            });

            console.log("Uploading files...", formData);

            fetch(this.config.uploadUrl, {
                method: "POST",
                body: formData
            })
                .then(response => response.text()) // Change from .json() to .text() for debugging
                .then(data => {
                    console.log("Server Response:", data);
                    alert("Upload Successful!");
                })
                .catch(error => {
                    console.error("Upload failed:", error);
                    alert("Upload Failed. Check console for details.");
                });
        }

// Initialize uploader

const uploader = new UniversalFileUploader({
  dropZoneSelector: '#file-drop-zone',
  maxTotalSize: 100 * 1024 * 1024, // 100MB
  maxFileSize: 50 * 1024 * 1024, // 50MB per file
  allowedTypes: ['image/jpeg', 'image/png', 'application/pdf']
});

There is vb code behind:

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
   If Request.Files.Count > 0 Then
     Dim uploadedFiles As HttpFileCollection = Request.Files
     Dim savedFiles As New List(Of String)()

     For i As Integer = 0 To uploadedFiles.Count - 1
         Dim file As HttpPostedFile = uploadedFiles(i)
         If file.ContentLength > 0 Then
             Dim savePath As String = Server.MapPath("~/Uploads/" & file.FileName)
             file.SaveAs(savePath)
             savedFiles.Add(file.FileName)
         End If
     Next

     Response.ContentType = "application/json"
     Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(New With {.success = True, .files = savedFiles}))
     Response.End()
   End If
End Sub

I added the enctype on form tab

<form id="form1" runat="server" enctype="multipart/form-data">

gtag is not sending custom event when redirecting to external page

I want to track when user clicks on the button which redirect to external page.
Implementation:

 gtag("event", name, {
    event_callback: () => onLinkOpen ? onLinkOpen(link) : window.open(link, "_self")
    transport: "xhr",
 })

config:

gtag("config", trackingId, {
  send_page_view: true,
})

But I don’t see any requests to /collect endpoint after redirection in Network tab. For events without redirection logic it works well

Issue with navigating to a deep nested route using CommonActions.reset in React Navigation

I am trying to navigate to RouteD using CommonActions.reset in React Navigation, but the navigation works inconsistently. Sometimes it successfully navigates, but most of the time, it fails.

        navigation.dispatch(
CommonActions.reset({
    index: 0,
    routes: [
        {
            name: 'RouteA',
            state: {
                index: 0,
                routes: [
                    {
                        name: 'RouteB',
                        state: {
                            index: 3,
                            routes: [
                                { name: 'RouteC1' }, // This route is conditional
                                { name: 'RouteC2' },
                                { name: 'RouteC3' },
                                {
                                    name: 'RouteD',
                                    params: {
                                       data: []
                                    }
                                },
                                { name: 'RouteE' }
                            ]
                        }
                    }
                ]
            }
        }
    ]
})
);

Issue Observed:

  • The navigation occasionally works as expected.
  • Most of the time, it fails, and the screen does not transition to RouteD.

Question:

  • Is there an issue with how I am structuring the CommonActions.reset state?
  • Are there any known limitations with deep navigation resets in React Navigation that could be causing this?

Would appreciate any insights or suggestions! Thanks in advance.

RTK Query Mutation with selector

I’ve used redux toolkit for a few years and I’m pretty familiar with it. I’m going through and attempting to update old code using the newer RTK Query strategy to replace some of my old slices and thunks.

If I’m understanding the docs correctly, it seems like RTK Query is meant to largely replace the old way of doing things, and instead of maintaining state “manually” in your slices, you let RTK Query handle management / caching, and you just re-request the data from the api slice that was defined by RTK Query, and it just does the rest automagically.

Assuming this to be correct, how do you select data that was added to the cache by a mutation?

Specifically, I’m using a mutation to authenticate a user (this is the simplest test scenario, so there’s really no auth, no tokens, etc.)

It looks like:

    loginUser: builder.mutation<UserServiceResult, UserCredentials>({
        query: ({ userName, password }) => ({
            url: '/authenticate',
            method: 'POST',
            body: { UserName: userName, Password: password },
        }),
    }),

In the login form, this is used like this:

    const [loginUser, { isLoading: isUpdating }] = useLoginUserMutation();
    loginUser(credentials).unwrap().then((userServiceResult) => {
        if (userServiceResult.isSuccessful) {
            console.log("Successfully logged in", userServiceResult);
            toast.success("User authenticated.", {position: "top-right"});
        } else {
            toast.error("User authentication failed.", {position: "top-right"});
        }
    })

This is all working fine. But the main layout is using a redux selector to check if the user exists in the store in order to show the “logged in” menu vs. the “guest” menu. It looks like this:

const user = useAppSelector(selectUser); // then do stuff if user is not null

What’s the strategy for getting data held in the API mutations?

enter image description here

how to find an element inside an iframe in k6/browser?

I’m trying to automate an interaction with a dynamic iframe using K6 Browser, but I’m facing difficulties when trying to click a button inside that iframe. The code I’m using is as follows:

const myFrame = 'iframe[src^="https://sandbox.clicksign.com/sign/"][src*="embedded=true"]';
      await page.waitForSelector(myFrame, {visible: true, timeout: 1000});
      const iframeElement = await page.$(myFrame);
      const iframeContent = await iframeElement.contentFrame();
      await iframeContent.click('//button[text()="Assinar"]');
      console.log(i)
      console.log(myFrame)

The iframe URL is dynamic and changes over time, but it follows a pattern where the URL starts with https://sandbox.clicksign.com/sign/ and contains embedded=true.

I get the following errors:

WARN[0052] Unexpected DevTools server error: context canceled category="ExecutionContext:eval" elapsed="0 ms" source=browser

ERROR[0052] Uncaught (in promise) clicking on "//button[text()="Subscribe"]": timed out after 30s

I tried using waitForSelector to wait for the iframe, but I still have issues.

Can anyone help me understand how I can handle dynamic iframe URL and click the button correctly inside it? What would be the best approach to do this, considering that the iframe URL is dynamic?

JS HTMLImageElement and garbage collection

Am I required to hold ref to HTMLImageElement to prevent it from being gc’ed befor its load/error events will be fired?

for example:

/**
 * @param { string[] } urls 
 * @returns { Promise<HTMLImageElement[]> }
 */
function loadImages(urls) {
    return new Promise(function(resolve) {
        /**@type { HTMLImageElement[] } */
        const images = [];
        let i = urls.length;
        /**@this { HTMLImageElement } */
        function onLoad() {
            images.push(this);
            if (--i === 0) resolve(images);
        }
        function onError() {
            if (--i === 0) resolve(images);
        }
        for (const url of urls) {
            const image = new Image();
            image.src = url;
            image.addEventListener("load", onLoad);
            image.addEventListener("error", onError);
        }
    });
}

is it possible to some of images being lost due to gc or not ?

it looks like i really need to do it, but there also can be some special rule for cases like this