JavaScript Doesn’t Always Load

I am trying to build a website, the JavaScript code that is supposed to add the sticky navigation menu when the header is not visible doesn’t work properly. It was working without any problems when I hosted the website locally; but, when I hosted the website on a server it doesn’t always work.

There are two JavaScript files for different stuff, one works flawlessly. The one that is causing problems is using JQuery, I surmise that maybe it is JQuery that is causing problems.

After reloading the site many times, it starts to work as intended. Also, this error shows up in console when this happens;

script.js:34 Uncaught ReferenceError: $ is not defined
    at script.js:34:5
(anonymous) @   script.js:34

Here are the codes that are causing problems.

The JavaScript file;

if (window.location.href.replaceAll(window.location.origin, '').replaceAll('/', '').length === 0 || window.location.href.includes("index.html")) {
    $(window).scroll
        (
            $(window).onload = function () {

                if ($(window).scrollTop() >= 300) {
                    $(window).innerWidth
                        (
                            function () {

                                if ($(window).innerWidth() < 460) {
                                    $('nav').addClass('fixed-header');
                                    $('nav div').removeClass('visible-title');
                                }
                                else {
                                    $('nav').addClass('fixed-header');
                                    $('nav div').addClass('visible-title');
                                }

                            }
                        );


                }
                else {

                    $('nav').removeClass('fixed-header');
                    $('nav div').removeClass('visible-title');
                }
            }
        );
} else {
    if ($(window).innerWidth() < 460) {
        $('nav').addClass('fixed-header');
        $('nav div').removeClass('visible-title');

    } else {
        $('nav').addClass('fixed-header');
        $('nav div').addClass('visible-title');
    }
}

The HTML file;

<!DOCTYPE html>
<html lang="tr">

    <head>
        <!-- Google tag (gtag.js) -->
        <script async
            src="https://www.googletagmanager.com/gtag/js?id=XXXXXX"></script>
        <script>
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());

        gtag('config', 'XXXXXX');
    </script>

        <script language="JavaScript" type="text/javascript" async src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <script language="JavaScript" type="text/javascript" async src="/script.js"></script>

        <script id="MathJax-script" async
            src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
        <title>Arşiv</title>
        <link rel="icon" type="image/x-icon" href="../RezonansLogo.png">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="../style.css">
    </head>

    <body>
        <header>
            <nav>
                <div class="site-title"><a
                        style="color:white; text-decoration: none"
                        href="../index.html"
                        target="_self">Rezonans Kulübü</a></div>
                <ul>
                    <li><a href="/sayfalar/yazilar.html">Yazılar</a></li>
                    <li><a href="/sayfalar/ekip.html">Ekip</a></li>
                    <ul>
                    </nav>
                </header>
                <section class="content">
                    <article>
                        <h1>Örnek.</h1>
                    </article>
                </section>
            </body>

        </html>

I tried loading the script inside the body tag but it didn’t helped at all. I tried downloading JQuery, it also didn’t solved the problem. I tried to remove the async tag, that somewhat worsened the issue. I also tried to incIude a JQuery fallback. I am out of ideas at this point.

Post Scriptum: I suppose these are very inefficient and absurd, sorry for that. Thank you in advance.

Getting weird error in Vue.js 3 while using i18n

I am working on a project where i18n is used, and the loader is ‘@intlify/vue-i18n-loader’. I am working with 2 languages: English and German. I am getting a weird error while running the app.

ERROR  Failed to compile with 1 error                                                                  2:59:59 PM

 error  in ./src/locales/de.json

Module parse failed: Cannot parse JSON: Unexpected token 'e', "export def"... is not valid JSON while parsing 'export default {
  "bch": {
    "bps": ('
File was processed with these loaders:
 * ./node_modules/@intlify/vue-i18n-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
Error: Cannot parse JSON: Unexpected token 'e', "export def"... is not valid JSON while parsing 'export default {
  "bch": {
    "bps": ('
    at JsonParser.parse (/Users/mohitchandel/Documents/front-end/node_modules/webpack/lib/json/JsonParser.js:54:10)

The weird thing is that I have never exported the JSON file mentioned in the Error and the file is in pure JSON format.

Here is my vue.config.js

const CircularDependencyPlugin = require("circular-dependency-plugin");
const ReplaceInFileWebpackPlugin = require("replace-in-file-webpack-plugin");
const webpack = require("webpack");
const path = require("path");

process.env.VUE_APP_VERSION = require("./package.json").version;

module.exports = {
    chainWebpack: (config) => {
        config.optimization.minimizer("terser").tap((args) => {
            args[0].terserOptions.output = {
                ...args[0].terserOptions.output,
                comments: false, // exclude all comments from output
                ascii_only: true,
            };
            return args;
        });
        config.module
            .rule("i18n")
            .test(/.json$/)
            .include.add(path.resolve(__dirname, "src/locales"))
            .end()
            .use("@intlify/vue-i18n-loader")
            .loader("@intlify/vue-i18n-loader")
            .end();
    },
    pluginOptions: {
        webpackBundleAnalyzer: {
            analyzerMode: process.env.VUE_APP_MODE === "production" ? "disabled" : "static",
            openAnalyzer: false,
        },
        i18n: {
            locale: "en",
            fallbackLocale: "en",
            localeDir: "locales",
            enableInSFC: true,
        },
    },
    configureWebpack: {
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "src"),
            },
            fallback: {
                stream: require.resolve("stream-browserify"),
                assert: require.resolve("assert/"),
                http: require.resolve("stream-http"),
                https: require.resolve("https-browserify"),
                os: require.resolve("os-browserify/browser"),
                url: require.resolve("url/"),
            },
        },
        plugins: [
            new webpack.ContextReplacementPlugin(/date-fns[/\]/, new RegExp(`[/\\](en|de)[/\\]index.js$`)),
            new CircularDependencyPlugin({
                exclude: /a.js|node_modules/,
                failOnError: true,
                allowAsyncCycles: false,
                cwd: process.cwd(),
            }),
            new ReplaceInFileWebpackPlugin([
                {
                    dir: "dist/static/img",
                    files: ["sheet.json", "sheet_holiday.json"],
                    rules: [
                        {
                            search: '"image": "sheet.png"',
                            replace: '"image": "sheet.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                        {
                            search: '"image": "characters.png"',
                            replace: '"image": "characters.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                        {
                            search: '"image": "mall.png"',
                            replace: '"image": "mall.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                        {
                            search: '"image": "sheet_holiday.png"',
                            replace: '"image": "sheet_holiday.png?v=' + process.env.VUE_APP_VERSION + '"',
                        },
                    ],
                },
            ]),
        ],
    },
    publicPath: "/",
    outputDir: "dist",
    runtimeCompiler: true,
    assetsDir: "static",
    productionSourceMap: false,
};

And here is my de.json

{
    "bch": {
        "bps": "Bytes pro Sekunde",
        "ctps": "{'@'}:btc.ctps",
        "difficulty": "{'@'}:btc.difficulty",
        "fiatPrice-usd": "{'@'}:btc.fiatPrice-usd",
        "halving": "{'@'}:btc.halving",
    },
    ....
}

Loading MongoDB Atlas collection into ram for each network request

I have a fixed size dataset (it won’t grow).

Here are the figures:

STORAGE SIZE: 190.13MB
LOGICAL DATA SIZE: 253.71MB
TOTAL DOCUMENTS: 53452
INDEXES TOTAL SIZE: 1.44MB

I don’t like the fact that I am loading the whole dataset into RAM for each network request

const data = await collection.find().toArray();

I could cache the table contents with a global variable.
I would like to know what are the optimal solutions for this case?
FYI. I need the entire table for each request to do comparator logic.

DataGrid. How change background color of header?

I need to change this white background Image Ref

<DataGrid
    rows={users}
    columns={columns}
    disableColumnMenu={true}
    hideFooter={true}
    loading={isLoading}
    autoHeight={true}
    sx={{
      boxShadow: 2,
      border: 2,
      borderColor: "#292524",
      "& .MuiDataGrid-cell": {
        color: "white",
        borderColor: "#292524",
      },
      "& .MuiDataGrid-columnHeader": {
        backgroundColor: "#0c0a09",
        color: "#75706c",
      }
    }}
/>

& .MuiDataGrid-columnHeader changes the color, but only of inner header cells

DataGrid. How change backround color of header?

enter image description here
Need to remove repaint or remove this white background

<DataGrid
    rows={users}
    columns={columns}
    disableColumnMenu={true}
    hideFooter={true}
    loading={isLoading}
    autoHeight={true}
    sx={{
      boxShadow: 2,
      border: 2,
      borderColor: "#292524",
      "& .MuiDataGrid-cell": {
        color: "white",
        borderColor: "#292524",
      },
      "& .MuiDataGrid-columnHeader": {
        backgroundColor: "#0c0a09",
        color: "#75706c",
      }
    }}
/>

& .MuiDataGrid-columnHeader changes color, but only of inner header cells

Difference between http and express

I’m trying to build a socket.io based application and I can’t seem to get the difference between http and express.

import express from 'express';
import http from 'http';
import {Server} from 'socket.io';

const app=express();
const server = http.createServer(app); 
const io=new Server(server,{
    cors:{
        origin:"http://localhost:3001"
    }
});

Why do I need http when it has the same functionality as express?
Could anyone explain this code?

How can I properly implement refresh token handling on the frontend in a React application?

So I have been trying to create a fullstack app that uses both an Access Token and refresh token, I have had success in past occassion with implementing access tokens but with refresh tokens I’m really struggling.

To give you some context: I have been working on the backend of the app and I have come up with:

//Tokens send with the login of the user:

 const accessToken = jwt.sign(
      {
        userId: foundUsername.rows[0].id_persona,
        username: foundUsername.rows[0].username,
        roles: foundRoles.rows,
      },
      process.env.JWT_SECRET_KEY as string,
      { expiresIn: "5m" }
    );

    const refreshToken = jwt.sign(
      {
        userId: foundUsername.rows[0].id_persona,
        username: foundUsername.rows[0].username,
      },
      process.env.JWT_SECRET_KEY as string,
      {
        expiresIn: "1d",
      }
    );

    res.cookie("refresh_cookie", refreshToken, {
      httpOnly: true,
      secure: false,
      sameSite: "none",
      maxAge: 24 * 60 * 60 * 1000,
    }); 
return res.json({ accessToken });

Now if I am not mistaken the refresh token is supposed to be holded in a local storage while the Refresh one is supposed to be the “cookie”.

this is the refresh the “access token” when asked to endpoint:

export const refreshAccess = async (req: Request, res: Response) => {
  // Check if the token exists
  const token = req.cookies["refresh_token"];
  if (!token) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  try {
    const decoded = jwt.verify(
      token,
      process.env.JWT_SECRET_KEY as string
    ) as JwtPayload;
    const result = await pool.query(
      "SELECT id_roles FROM assignated_roles WHERE id_persona = $1",
      [decoded.userId]
    );

    const foundRoles = result.rows.map((row) => row.id_roles);
    const accessToken = jwt.sign(
      {
        userId: decoded.userId,
        username: decoded.username,
        roles: foundRoles,
      },
      process.env.JWT_SECRET_KEY as string,
      { expiresIn: "5m" }
    );

    return res.json({ accessToken });

I am satisfied with these Endpoints. I have tested them and they work… in theory.
But here come my big questions that I have been asking myself before even finishing my login.

How am I supposed to reach these endpoints? I was inspired to create and use Refresh/Access token becouse of this post: https://designtechworld.medium.com/how-to-authenticate-using-access-and-refresh-tokens-using-react-js-57756df2d282

Now in said post the way the Access Token is being refreshed its through a timer… That.. Can’t be right no? I was thinking about holding the data in a context so I could make protected Routes later on. But in order to do so. I would have to constantly make requests with each click the user make. So I would be constantly asking the DB for information. Which again doesn’t seem right.

As you might have noticed I feel frozen becouse I have so many ways I feel like this could be implemented.

I would like some guidance as to what are best practices when it comes to the implementation of Refresh/Access tokens when it comes to the frontend(React).

With that being said, any feedback on how to properly create a working frontend would be really appreciated.

Thank you for your time!

is there a node package tailored for high-fidelity conversion from doc to html5 code?

I’m developing a NEXTjs app that allows user to view their docx files in the browser, the goal is to convert the file from word to html code with proper formatting, ps: html should not be editable

Im currently using mammoth.js but it doesn’t seems to be working below is the component

export default function Home() {
  const [htmlContent, setHtmlContent] = useState("");

  const handleFileUpload = async (event) => {
    const file = event.target.files[0];
    if (
      file &&
      file.type ===
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    ) {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const arrayBuffer = e.target.result;
          const options = {
            styleMap: [
              "p.Heading1 => h1",
              "p.Heading2 => h2",
              "p.Heading3 => h3",
              "p.Heading4 => h4",
              "p.Heading5 => h5",
              "p.Heading6 => h6",
              "p[style-name='Title'] => h1.title",
              "p[style-name='Subtitle'] => h2.subtitle",
              "p[style-name='Quote'] => blockquote",
              "table => table.table-bordered",
              "p => p.paragraph",
              "r[style-name='Bold'] => strong",
              "r[style-name='Italic'] => em",
            ],
            convertImage: mammoth.images.imgElement((image) => {
              return image.read("base64").then((imageBuffer) => {
                return {
                  src: "data:" + image.contentType + ";base64," + imageBuffer,
                };
              });
            }),
          };
          const result = await mammoth.convertToHtml(
            { arrayBuffer },
            options
          );
          setHtmlContent(result.value);
        };
        reader.readAsArrayBuffer(file);
      } catch (error) {
        console.error(error);
      }
  };

  const handleSaveHtml = () => {
    const blob = new Blob([htmlContent], { type: "text/html;charset=utf-8" });
    saveAs(blob, "converted-document.html");
  };

  return (
    <>
      <main className={styles.main}>
        <input type="file" onChange={handleFileUpload} accept=".docx" />
        {htmlContent && (
          <div>
            <h2>Converted HTML:</h2>
            <div
              dangerouslySetInnerHTML={{ __html: htmlContent }}
              style={{
                backgroundColor: "#fff",
                color: "#000",
                padding: "20px",
                borderRadius: "8px",
                lineHeight: "1.6",
                fontFamily: "Arial, sans-serif",
              }}
            />
            <button onClick={handleSaveHtml} style={{ marginTop: "20px" }}>
              Save HTML
            </button>
          </div>
        )}
      </main>
    </>
  );
}

Issue:
The problem is that when I upload a .docx file, the conversion does not work as expected. The HTML output is either not rendered at all or rendered incorrectly. There are no specific errors in the console, but the document’s content is not being displayed properly in the browser.

What I’ve Tried:
I’ve ensured that the file being uploaded is a valid .docx file.
I’ve verified that the file type is correctly identified as “application/vnd.openxmlformats-officedocument.wordprocessingml.document”.

I’ve tried adjusting the styleMap to ensure proper mapping of Word styles to HTML elements.
I’ve checked the browser console for any errors, but nothing significant shows up.

Environment:
Next.js version: 14.2.5
mammoth.js version: 1.4.2
file-saver version: 2.0.5
Browser: Chrome 104

Question:
What could be causing mammoth.js to fail in converting the DOCX file to HTML properly, and how can I fix this issue to ensure that the HTML is rendered correctly in the browser?

Add functionality to ajax_add_to_cart button in woocommerce to close a custom modal after item was added to cart

Im trying to close a modal with javascript (doesnt matter if its with js or jquery or php), I’ve tried adding custom JS with a button pointer like this:

<script type="text/javascript">
(function($){
   $('.btn[data-product_id='11068651']').click( function(){
      document.querySelector(".speak-up-modal").style.display = "none";
   });
   $('.btn[data-product_id='11068652']').click( function(){
      document.querySelector(".speak-up-modal").style.display = "none";
   });
})(jQuery);
</script>

And add this to the wp_footer this way:

add_action( 'wp_footer', 'single_add_to_cart_event_button_function' );
function single_add_to_cart_event_button_function() {
    ?>
        <script type="text/javascript">
            (function($){
                $('.btn[data-product_id='11068651']').click( function(){
                    document.querySelector(".speak-up-modal").style.display = "none";
                });
                $('.btn[data-product_id='11068652']').click( function(){
                    document.querySelector(".speak-up-modal").style.display = "none";
                });
            })(jQuery);
        </script>
    <?php
}

But nothing works, this is how Im using the woocommerce buttons in the modal:

<a href="#" class="button add_to_cart_button ajax_add_to_cart btn" data-product_id="11068652" data-quantity="1" rel="nofollow">

And nothing I do adds the event to the button, any chance for some help in modifying/adding functionality to this button?

This is what I’ve tried:
Button:

<a href="#" class="button add_to_cart_button ajax_add_to_cart btn" data-product_id="11068652" data-quantity="1" rel="nofollow">

Inside the JS in footer itself where I initiate the modal

<script type="text/javascript">
(function($){
   $('.btn[data-product_id='11068651']').click( function(){
      document.querySelector(".speak-up-modal").style.display = "none";
   });
   $('.btn[data-product_id='11068652']').click( function(){
      document.querySelector(".speak-up-modal").style.display = "none";
   });
})(jQuery);
</script>

And in functions.php:

add_action( 'wp_footer', 'single_add_to_cart_event_button_function' );
function single_add_to_cart_event_button_function() {
    ?>
        <script type="text/javascript">
            (function($){
                $('.btn[data-product_id='11068651']').click( function(){
                    document.querySelector(".speak-up-modal").style.display = "none";
                });
                $('.btn[data-product_id='11068652']').click( function(){
                    document.querySelector(".speak-up-modal").style.display = "none";
                });
            })(jQuery);
        </script>
    <?php
}

Generating TOTP using OTPAuth library on Nodejs

I do face some problem while generating TOTP by OTPAuth library on Nodejs. Sometimes, time on my devices is not correct, so it led to the incorrect in TOTP generated. I can prevent it by set the right time for my device.

I wonder do we have any way to make sure that the OTPAuth library generate based on the correct time not by manually set time on device?

How can I edit the Date format? [duplicate]

I have an application which can be used to organize exams. There is a span to demonstrate registration date. Here is how I did it:

let getDate = new Date();

But the thing is it shows whole information about time but I only need date and month. E.g. 12 March.

So can you please suggest any method or piece of code to do this?

The useEffect hook in React does not render all changes on Safari

I’m trying to write a web game with WebSocket synchronization. In my React app, I receive updates via WebSocket to update the view of the application. My problem is that when I receive multiple messages successively, my useEffect only considers the last one. I think this is due to an optimization in React. My code works well on Chrome, but it doesn’t work in Safari. How can I fix this?

Code:

const { message, sendMessage, setUrl } = useWebSocket();
useEffect(() => {
    console.log(message);
    if (message && sessionJeu != true) {
      setSessionJeu(true);
    }

    if (message.type == "end") {
      setSessionJeu(false);
    }
  }, [message]);

Logs:

My logs on safari

You can see what my WebSocket hook prints first and what the useEffect prints at the last line.

My code works in Chrome, so I’m sure that the error is in this part.

If necessary, I can provide more information. I hope this is clear.

IsNumeric function is not working when the value is “0”

I have this JavaScript function in my Razor page to check if the value is numeric.

When a “0” is passed to this function, it will return as false. I have tested the expression in other RegEx tester and “0” is a valid match. If the input parameter is “0.0”, it will be ok.

Any idea what went wrong? Please advise. Thanks.

function isNumericValid(value) {
  var result = false;
  if (value != "") {
    // up to 12 digits and 10 dec places
    let template = /^-{0,1}d{1,12}(.d{1,10})?$/;

    if (template.test(value))
      result = true;
  }
  return result;
}

console.log(isNumericValid("0"))
console.log(isNumericValid(0))
console.log(isNumericValid("0.0"))
console.log(isNumericValid(0.0))
console.log(isNumericValid(1234.10))

How to get user regional settings in a browser? Not user language

My Windows11 language is english but my regional settings is set to danish.

When I run the below code ‘en-GB’ is returned. I expected ‘da-DK’ to be returned.

    function getUserLocale() {
        const intl = window.Intl;
        if (intl !== undefined) {
            return intl.NumberFormat().resolvedOptions().locale;
        }

        // Old standard.
        return navigator.language ?? "en-US";
    }

Lodash how to sort a group with custom sequence?

Currently the response that are being sent back to client side looks like this:

[
  {
    "categoryName": "Orders",
    "categorySettings": ...the rest
  },
  {
    "categoryName": "Notifications",
    "categorySettings": ...the rest
  },
  {
    "categoryName": "Personalisation",
    "categorySettings": ...the rest
  }
]

However, the expected layout is:

[
  {
    "categoryName": "Personalisation",
    "categorySettings": ...the rest
  },
  {
    "categoryName": "Notifications",
    "categorySettings": ...the rest
  },
  {
    "categoryName": "Orders",
    "categorySettings": ...the rest
  }
]

How do I sort the categoryName to match the order that I expected? I am thinking about matching the sort order to an array of object with “categoryName” and “sequence” properties, but I am stuck at the code.

My current code is as below:

const groupedData = _.chain(allData)
      .groupBy('sectionName')
      .map((allData, sectionName) => ({
        categoryName: sectionName,
        categorySettings: _.chain(allData)
          .groupBy('group')
          .map((groupSettings, group) => ({
            group: group,
            groupSettings: _.chain(groupSettings)
              .sortBy('ordering')
              .groupBy('title')
              .map((titleSettings, title) => ({
                settingName: title,
                settingDescription: titleSettings[0].description,
                settingInputs: _.map(titleSettings, ({name, value, inputSetting}) => ({
                  inputName: name,
                  inputValue: value,
                  inputConfig: inputSetting,
                })),
              }))
              .value(),
          }))
          .value(),
      }))
      .value();