Google Ads conversion events seem to be firing on every page in a single-page application

I have integrated Google Ads conversion tracking in my AngularJS application. I have two simple conversion events that are being added to the DOM dynamically, each on a different page. Both of them are added to the DOM like this, depending on the url of the page:

       if (toParams.key === 'example-page') {
            if (!document.getElementById('thankYouConversionScript')) { // Check if script doesn't already exist
                var refElement = document.getElementById('phoneScript');
                if (refElement) {
                    var inlineScript = document.createElement('script');
                    inlineScript.id = 'thankYouConversionScript'; // Assign ID to the script
                    inlineScript.text = 'gtag('event', 'conversion', {"send_to": "AW-xxxxxxx/xxxxxxxxxxxx"});';
                    refElement.parentNode.insertBefore(inlineScript, refElement.nextSibling);
                }
            }
        }

When testing the system using the Google Tag Assistant(legacy) I noticed a weird behaviour. The first time the script is added to the page, it fires correctly. However, after navigating to the other page, where the second script is added to the DOM, the Google Tag Assistant shows both the new conversion event as well as the the old one.
When testing the system with the modern Tag Assistant, everything seems to be okay – only one new conversion event is added.

I have tried removing the scripts from the dom when navigating to another page, but the list still shows both conversion events.

Is this just an issue with legacy Google Tag Assistant or am I doing something wrong?

How to open a input box with save button when input value got increased

I have a “Master” table where user will fill all the details and press the save button. Also there is a certain limit for all input data. if the input value is increased beyond the set limit due to some reason then User have to mention the reason and save it. Basically the input box for reason is in hidden condition if the value is increased then only it will pop up on screen with save button.

I have tried with visibility class. Below are the codes.

document.getElementById("btn1").addEventListener("click", first);

function first() {

  let prodDetails = {};
  productionDetails.input1 = document.getElementById("master").rows[0].cells[1].children[0].value;
  productionDetails.input2 = document.getElementById("master").rows[0].cells[2].children[0].value;
  productionDetails.input3 = document.getElementById("master").rows[0].cells[3].children[0].value;

  google.script.run.dataSave1(prodDetails1);

  let sd = document.getElementById("master").rows[0].cells[1].children[0].value;
  if (sd > 0) {
    comment();
  }

  function comment() {
    document.getElementById("bd1").style.visibility = "visible";
  }
  .popup {
  width: 550px;
  height: 200px;
  position: absolute;
  top: 50%;
  left: 40%;
  background-color: #fff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  visibility: hidden;
<base target="_top">

<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form action="submitscript.php" target="dummyframe">
  <table id="master">
    <tbody>
      <tr>
        <td style="background-color:#00FF00"><label><b>Good Parts Qty</b></label></td>
        <td><input type="number" value="0" min="0" required></td>
        <td><input type="number" value="0" min="0" required></td>
        <td><input type="number" value="0" min="0" required></td>
      </tr>
      <tr>
        <td><label> </label>
          <td><button id="btn1">Save</button></td>
      </tr>
      <div class="popup">
        <input type="text" id="bd1" placeholder="Enter breakdown details">
        <button id="btn"> Submit </button>
      </div>

How can I load SCSS styles globally using Webpack 5 in a React 18 project, instead of importing styles into each component?

I’m working on a React 18 project and I want to load my SCSS styles globally using Webpack 5 configuration, rather than importing each style file into its respective components.

Currently, I’m importing SCSS files in individual components like this:

// src/components/AuthSSO/Login.tsx
import "../../styles/new.scss"

However, I’d prefer to set up my Webpack 5 configuration to load these styles globally for the entire application. This would help reduce redundant imports and make style management more centralized.

Here’s my current Webpack 5 configuration (relevant parts):

const path = require("path")
const OutputPath = path.resolve(__dirname, "../build")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const TerserPlugin = require("terser-webpack-plugin")
require("css-minimizer-webpack-plugin")
if (process.env.NODE_ENV !== "production") {
  console.log("Development mode")
}
module.exports = (env, argv) => {
  const devMode = argv.mode !== "production"

  return {
    entry: {
      index: "./src/webpack/index.tsx",
      styles: ["./src/styles/main.scss", "./src/styles/main-dark.scss"],
    },
    output: {
      filename: devMode ? "js/[name].js" : "js/[name].[contenthash].js",
      path: OutputPath,
      publicPath: "/",
      assetModuleFilename: "assets/[name][ext][query]",
    },
    devtool: devMode ? "eval-cheap-source-map" : false,
    devServer: {
      historyApiFallback: true,
      open: true,
      host: "localhost",
      port: 8080,
      hot: false,
      client: {
        overlay: {
          warnings: true,
          errors: true,
        },
      },
      proxy: {
        "/api": {
          target: "http://localhost:8000", // Local
          changeOrigin: true,
        },
      },
    },
    performance: {
      hints: false,
    },
    module: {
      rules: [
        {
          test: /.(ts|tsx)$/,
          use: "ts-loader",
          exclude: /node_modules/,
        },
        {
          test: /.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
          },
        },
        {
          test: /.(sa|sc|c)ss$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
            },
            {
              loader: "css-loader",
            },
            {
              loader: "postcss-loader",
              options: {
                postcssOptions: {
                  plugins: () => [require("autoprefixer"), require("precss")],
                },
              },
            },
            {
              loader: "sass-loader",
            },
          ],
        },
        {
          test: /.(png|svg|jpg|jpeg|gif)$/i,
          type: "asset/resource",
        },
      ],
    },
    resolve: {
      extensions: [".tsx", ".ts", ".js"],
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
            test: /[\/]node_modules[\/]/,
            name: "vendor",
            chunks: "all",
          },
        },
      },
      minimizer: [
        new TerserPlugin({
          extractComments: false,
        }),
      ],
    },
    plugins: [
      new CleanWebpackPlugin({
        cleanOnceBeforeBuildPatterns: ["css", "js", "fonts", "img/webpack"],
      }),
      new HtmlWebpackPlugin({
        template: "./public/index.html",
        filename: "index.html",
        inject: true,
      }),
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // all options are optional
        filename: devMode ? "css/[name].css" : "css/[name].[contenthash].css",
        chunkFilename: devMode
          ? "css/[name].css"
          : "css/[name].[contenthash].css",
        ignoreOrder: false, // Enable to remove warnings about conflicting order
      }),
    ],
    stats: {
      children: false,
    },
    externals: {
      Config: JSON.stringify(
        process.env.NODE_ENV === "production"
          ? {
              serverUrl: "",
            }
          : {
              serverUrl: "http://localhost:8000",
            }
      ),
    },
  }
}

index.tsx

import React from "react"
import ReactDOM from "react-dom/client"
// eslint-disable-next-line import/no-named-as-default
import App from '../App'
import 'bootstrap-icons/font/bootstrap-icons.css'
import '../styles/main.scss' // <-- this import is not working ( Tying to achive like this or to get rid of this )

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
)
root.render(
  <React.StrictMode>
      <App />
  </React.StrictMode>
)

What changes do I need to make to my Webpack 5 configuration to achieve global SCSS loading? Are there any potential drawbacks or considerations I should be aware of when implementing this approach?

Thank you in advance for your help!

I have tried different solutions from all over the web

I’ve tried to configure from above solutions:

  • I configured my Webpack setup to include SCSS files in the entry option.
  • I used MiniCssExtractPlugin to extract the styles into separate CSS files.
  • My Webpack configuration includes loaders for SCSS (sass-loader, css-loader, postcss-loader), and everything seems to be in order.
  • The styles are being bundled, but they’re not being applied globally as expected. I still need to import the styles manually in each component for them to take effect.

What I Expected:

I expected the global SCSS styles to be automatically applied across all components in my React application, without the need to import them in every individual component file.

How to capture click event by parent element when a child element disabled?

I want to capture click event by parent element when a child element disabled, like this codes

<div><button disabled>button</button></div>

where div has a clickevent

document.querySelector('div').addEventListener('click', () => {dosomething}, { capture: true })

When I click this button, the event will not be captured by div (standard), but I want this div to capture this event. How can I do this?

pointer-events:none does not work for me because I need to use document.elementsFromPoint() to get this button and do something. And pointer-events:none will cause the button to not be retrieved by this function

Delete div and label for that div without label id

Using Crispy forms in Django app, I the HTML code:

<div id="div_id_pripadnost" class="form-group"> <label for="id_pripadnost_0" class="">
               Pripadnost
           </label> 
<div class="">
<div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_1" value=""> <label for="id_pripadnost_1" class="form-check-label">
           ---------
       </label> </div>
<div class="form-check"> <input type="radio" class="form-check-input" checked="checked" name="pripadnost" id="id_pripadnost_2" value="CRS"> <label for="id_pripadnost_2" class="form-check-label">
           CRS
       </label> </div>
<div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_3" value="SCM"> <label for="id_pripadnost_3" class="form-check-label">
           SCM
       </label>
</div> </div> </div>

I would like to remove div with id="id_pripadnost_1". I have removed radio button/div "form-check", but I can’t remove label '---------', since it doesn’t have an id. How can you remove that label?

I have tried:

            const radioBtn = document.getElementById('id_pripadnost_1');
            radioBtn.style.display = 'none';
            radioBtn.previousElementSibling.style.display = 'none';
            document.getElementById('id_pripadnost_1').remove();

React Issue – Multiple items will be add in Cart

“I’m having an issue where, when I add an item to the cart, it seems to be adding all items at once, instead of just the one I clicked on.”

enter image description here

FoodItem.jsx File ->

import React, { useContext } from 'react'

import './FoodItem.css'
import { assets } from '../../assets/assets'
import { StoreContext } from '../../context/StoreContext'


const FoodItem = ({id, name, price, description, image}) => {


    const {cartItems,addToCart,removeFromCart} = useContext(StoreContext);

    return (
    <div className='food-item'>
        <div className="food-item-img-container">
            <img className='food-item-image' src={image} alt=''></img>
            {
                !cartItems[id]
                ?<img className="add" onClick={() => addToCart(id)} src={assets.add_icon_white} alt=''></img>
                :<div className='food-item-counter'>
                    <img onClick={()=>removeFromCart(id)} src={assets.remove_icon_red} alt="" />
                    <p>{cartItems[id]}</p>
                    <img onClick={()=>addToCart(id)} src={assets.add_icon_green} alt=''></img>

                </div>
            }
        </div>
        <div className="food-item-info">
            <div className="food-item-name-rating">
                <p>{name}</p>
                <img src={assets.rating_starts} alt=''></img>
            </div>
            <p className="food-item-desc">
                {description}
            </p>
            <p className="food-item-price">
                 &#8377;{price}
            </p>
        </div>
      
    </div>
  )
}

export default FoodItem

StoreContext.jsx File ->

import { createContext, useEffect, useState } from "react";
import { food_list } from "../assets/assets";

export const StoreContext = createContext({});

const StoreContextProvider = (props) => {

    const [cartItems, setCartItems] = useState({});

    const addToCart = (itemId) => {
        if(!cartItems[itemId]){
            setCartItems((prev)=>({...prev,[itemId]:1}))
        }
        else{
            setCartItems((prev)=>({...prev,[itemId]:prev[itemId]+1}))
        }
    }

const removeFromCart = (itemId) => {
      
            setCartItems((prev)=>({...prev,[itemId]:prev[itemId]-1}))
        }
            
        useEffect(() => {
            console.log(cartItems)
        },[cartItems])

    const contextValue = {

        food_list, 
        cartItems,
        setCartItems,
        addToCart,
        removeFromCart

    }

    return (
        <StoreContext.Provider value={contextValue}>
            {props.children}
        </StoreContext.Provider>
    )

}


export default StoreContextProvider;

I tried checking the addToCart function to ensure that it’s only updating the state for the specific item I clicked on. I also reviewed the component to make sure it’s correctly receiving and displaying the cartItems state. Additionally, I added a console.log to see if the itemId passed to the function matches the item being clicked.

Show and hide images using dropdown (js , html)

Was trying to make a multipurpose calendar application
Currently i only need fron August…

$('#aug').hide
$('#sep').hide
$('#oct').hide
$('#nov').hide
$('#dec').hide

function aug() {
  $('#aug').show
  $('#sep').hide
  $('#oct').hide
  $('#nov').hide
  $('#dec').hide
}

function sep() {
  $('#aug').hide
  $('#sep').show
  $('#oct').hide
  $('#nov').hide
  $('#dec').hide
}

function oct() {
  $('#aug').hide
  $('#sep').hide
  $('#oct').show
  $('#nov').hide
  $('#dec').hide
}

function nov() {
  $('#aug').hide
  $('#sep').hide
  $('#oct').hide
  $('#nov').show
  $('#dec').hide
}

function dec() {
  $('#aug').hide
  $('#sep').hide
  $('#oct').hide
  $('#nov').hide
  $('#dec').show
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<div class="page-1" id="page-1">
  <div class="calender" id="calender">
    <select name="" id="">
      <option value="">Jan</option>
      <option value="">Feb</option>
      <option value="">Mar</option>
      <option value="">Apr</option>
      <option value="">May</option>
      <option value="">Jun</option>
      <option value="">Jul</option>
      <option value="">Aug</option>
      <option value="">Sep</option>
      <option value="">Oct</option>
      <option value="">Nov</option>
      <option value="">Dec</option>
    </select>
    <div id="img-grp" class="img-grp">
      <img src="" alt="Jan" id="Jan">
      <img src="" alt="Feb" id="Feb">
      <img src="" alt="Mar" id="mar">
      <img src="" alt="Apr" id="Apr">
      <img src="" alt="May" id="may">
      <img src="" alt="Jun" id="jun">
      <img src="" alt="Jul" id="jul">
      <img src="months-png/aug.png" alt="Aug" onclick="aug()" id="aug">
      <img src="months-png/sep.png" alt="Sep" onclick="sep()" id="sep">
      <img src="months-png/oct.png" alt="Oct" onclick="oct()" id="oct">
      <img src="months-png/nov.png" alt="Nov" onclick="nov()" id="nov">
      <img src="months-png/dec.png" alt="Dec" onclick="dec()" id="dec">
    </div>
  </div>

I tried using jquery, $('#aug').hide
but it just gave
the page

can anyone pls help

there are also some extra code which shows the time and more images…

more details : it is running locally, and have no plans to host..
according to visual studio code , there are no problems in the code…
google chrome also says there are no problems inn the code., Atleast it doesnt show up in the console

Razorpay Payment Failure Redirection Prevents User Interaction with Button in React

I’m integrating Razorpay into my React project for handling payments. The payment flow works, but I’m facing an issue when a payment fails. Specifically, after a payment failure, the page redirects to the failure page, but I cannot interact with a button on that page. In the browser’s network tab, I can see that the request returns a status 200 for the initiator @trycatch.ts:180, but the button remains unclickable.

Code:

const App = () => {
  const loadScript = (src) => {
    return new Promise((resolve) => {
      const script = document.createElement("script");
      script.src = src;
      script.onload = () => {
        resolve(true);
      };
      script.onerror = () => {
        resolve(false);
      };
      document.body.appendChild(script);
    });
  };

  useEffect(() => {
    loadScript("https://checkout.razorpay.com/v1/checkout.js");
  }, []);

  const handlePayment = async () => {
    if (!loadingCourseInformation && courseInfo && !loadingCreateOrder) {
      try {
        setProcessingPayment(true);
        const amount = appliedDiscount ? appliedDiscount : courseInfo.price;
        const payload = {
          amount: amount.toString(),
          currency: "INR",
          course_id: courseInfo.course_id.toString(),
        };

        await createOrderPayload(payload);
      } catch (err) {
        setProcessingPayment(false);
        if (err.response) {
          notifyUser(
            "Order Error",
            "An error occurred while creating the order.",
            "error"
          );
        } else if (err.request) {
          notifyUser(
            "Network Error",
            "Network error, please try again.",
            "warning"
          );
        } else {
          notifyUser(
            "Unexpected Error",
            `Unexpected error: ${err.message}`,
            "error"
          );
        }
      }
    }
  };

  useEffect(() => {
    if (createOrderData) {
      setProcessingPayment(true);
      const amount = appliedDiscount ? appliedDiscount : courseInfo.price;
      const options = {
        key: userData.REACT_APP_RAYZOR_KEY,
        amount: amount * 100,
        currency: "INR",
        name: "MIT",
        description: courseInfo.course_name,
        image: mtsLogo,
        order_id: createOrderData.orderId,
        handler: async (response) => {
          const verifyPayload = {
            razorpay_order_id: response.razorpay_order_id,
            razorpay_payment_id: response.razorpay_payment_id,
            razorpay_signature: response.razorpay_signature,
          };
          try {
            await verifyOrderPayload(verifyPayload);
            razorpay.close();
          } catch (verificationError) {
            console.log(verificationError);
          }
        },
      };

      const razorpay = new window.Razorpay(options);

      razorpay.open();
      razorpay.on("payment.failed", function (response) {
        razorpay.close();
        setProcessingPayment(false);
        console.error("Payment failed:", response.error);
        navigate(`/app/payment/failure/${createOrderData.payment.payment_id}`);
      });
    }
  }, [createOrderData]);

  return (
    <>
      <Button
        onClick={handlePayment}
        fullWidth
        variant="outlined"
        className="course-price-wrapper__button-wrapper--buy-now"
      >
        Buy Now
      </Button>
    </>
  );
};

ReferenceError: exports is not defined (Vue.js)

When running my Vue project, I have suddenly ran into this issue.
ReferenceError: exports is not defined
It specifically appears in the framework.mjs file.
Object.defineProperty(exports, "__esModule", {

Tried deleting the whole Jest section in my package.json and even excluding “mjs” files from transform and moduleFileExtensions.
Here’s my package.json:

{
  "name": "test-project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^3.2.13",
    "vuetify": "^3.7.0-beta.1",
    "vuex": "^4.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@babel/plugin-transform-modules-commonjs": "^7.24.8",
    "@babel/preset-env": "^7.25.3",
    "@mdi/font": "^7.4.47",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-unit-jest": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/test-utils": "^2.4.6",
    "@vue/vue3-jest": "^27.0.0-alpha.1",
    "babel-jest": "^27.5.1",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "jest": "^27.0.5",
    "sass": "^1.77.8",
    "sass-loader": "^16.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {},
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)",
          "**/tests/unit/**/*.spec.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  ],
  "jest": {
    "preset": "@vue/cli-plugin-unit-jest",
    "setupFilesAfterEnv": ["<rootDir>/tests/unit/jest.setup.js"],
    "transform": {
      "^.+\.(js|jsx|ts|tsx|mjs)$": "babel-jest",
      "^.+\.vue$": "@vue/vue3-jest"
    },
    "moduleFileExtensions": [
      "js",
      "jsx",
      "ts",
      "tsx",
      "vue",
      "mjs"
    ],
    "transformIgnorePatterns": [
      "/node_modules/(?!(vuetify|@mdi|@vue/runtime-core)/)"
    ]
  }
}

Also, here’s the github with the complete project in case there’s something elsewhere that’s causing the problem:
https://github.com/PunkPimster/test-project

Please tell me if I need to add something else.

Redirect link from search or category to an existing page to show results with filters

I have a listings website main page and i want :

  1. when the user clicks on a category to redirect him to an existing page that shows list of the listings but with that specific category (eg when i click oil category open the page and show the results from the oil category)
<div class="main_categories">
 <div class="container">
                <ul class="clearfix">
                    <li>
                        <a href="grid-listings-filterscol.html">
                            <i class="fa-solid fa-bottle-droplet"></i>
                            <h3>Λάδι</h3>
                        </a>
                    </li>
                    <li>
                        <a href="grid-listings-filterscol.html">
                            <i class="fa-solid fa-apple-whole"></i>
                            <h3>Φρούτα</h3>
                        </a>
                    </li>
                    <li>
                        <a href="grid-listings-filterscol.html">
                            <i class="fa-solid fa-seedling"></i>
                            <h3>Λαχανικά</h3>
                        </a>
                    </li>
                    <li>
                        <a href="grid-listings-filterscol.html">
                            <i class="fa-solid fa-jar"></i>
                            <h3>Μέλι</h3>
                        </a>
                    </li>
                    <li>
                        <a href="grid-listings-filterscol.html">
                            <i class="fa-solid fa-ellipsis"></i>
                            <h3>Περισσότερα</h3>
                        </a>
                    </li>
                </ul>
            </div>
            <!-- /container -->
        </div>
  1. Same with search bar –> show results to the list page with the filters already selected
<section class="hero_single version_2">
            <div class="wrapper">
                <div class="container">
                    <h3>ΕΛΛΗΝΙΚΑ ΠΡΟΙΟΝΤΑ</h3>
                    <p>Ανακάλυψε τους καλύτερους παραγωγούς φυσικών προιόντων στην Ελλάδα.</p>
                    <form method="post" action="grid-listings-isotope.html">
                        <div class="row g-0 custom-search-input-2">
                            <div class="col-lg-4">
                                <div class="form-group">
                                    <input class="form-control" type="text" placeholder="Τι ψάχνεις...">
                                    <i class="icon_search"></i>
                                </div>
                            </div>
                            <div class="col-lg-3">
                                <div class="form-group">
                                    <select class="wide">
                                        <option>Όλες οι περιοχές</option>   
                                        <option>Αττική</option>
                                        <option>Πελοπόννησος</option>
                                        <option>Στερεά Ελλάδα</option>
                                        <option>Κρήτη</option>
                                        <option>Βόρεια Ελλάδα</option>
                                        <option>Νησιά Αιγαίου</option>
                                        <option>Νησιά Ιονίου</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-lg-3">
                                <select class="wide">
                                    <option>Όλες οι κατηγορίες</option> 
                                    <option>Λάδι</option>
                                    <option>Φρούτα</option>
                                    <option>Λαχανικά</option>
                                    <option>Μέλι</option>
                                    <option>Ζωοτροφές</option>
                                    <option>Βιολογικά</option>
                                </select>
                            </div>
                            <div class="col-lg-2">
                                <input type="submit" value="Αναζήτηση">
                            </div>
                        </div>
                        <!-- /row -->
                    </form>
                </div>
            </div>
        </section>

Is it possible to achieve this with Javascript – Jquery?

Thank you in advance

I have this on the list page and it works but i don’t know how to connect 2 pages

<script>$(window).on('load', function(){var $container = $('.isotope-wrapper');$container.isotope({ itemSelector: '.isotope-item', layoutMode: 'masonry' });});
$('.category_filter').on( 'click', 'input', 'change', function(){   var selector = $(this).attr('data-filter');   $('.isotope-wrapper').isotope({ filter: selector });  }); $('.city_filter').on('click', 'input', 'change', function(){   var selector = $(this).attr('location-filter');   $('.isotope-wrapper').isotope({ filter: selector }); }); </script> <script>   $('.filters_listing').on( 'click', 'input', 'change', function(){   var selector = $(this).attr('popular-filter');   $('.isotope-wrapper').isotope({ filter: selector }); }); </script>

JavaScript scope, clouser and reference [duplicate]


function foo() {
    var a = 'foo a';

    return {
        a: function() {
          return this.a;
        },
        b: function() {
          return a;
        }
    }
}

var a = 'global a';

foo().a() // still return reference to the function same as foo().a
foo().a()();
foo().b();

Hello anybody.

Could you tell me why for.a() doesn’t return value, instead the foo.a()() does?!
I don’t get it. Thanks!

I tested on Chrome browser

Persistent 404 fetch ERROR –> “POST http://localhost:3000/Custard/data/Pudding 404 (Not Found)”

I’m working on a game and want to save user button click and scores data on the server to be accessible at the address http://localhost:3000/Custard/data/{playerName}. The idea is that players can view their score in comparison to other players, and that they can navigate to other players routes to view the data. The data is stored in JSON format.

My code is buggy and I keep triggering either a 404 error or a 500 ECONNREFUSED internal Server Error. Also, when I navigate to http://localhost:3000/Custard/data/Pudding for example, all I get it is the game screen, not an empty page and not any results.

I’ve included my server-side and parts of client-side index.js files.

Server-Side index.js:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

const code = "code";
app.post(`/Custard/data/${code}`, (req, res) => {
    try {
        const data = dateien;
        console.log('Received data:', data);
        // Process the data as needed
        res.status(200).json({ message: 'Data received successfully', data: data });
    } catch (error) {
        console.error('Error processing data:', error);
        res.status(500).json({ message: 'Internal Server Error' });
    }
});

app.listen(3001, () => {
    console.log('Server is running on port 3000');
});

module.exports = app;

Client-Side index.js:

function sendDataToServer(code, button1Val, button1Col, button2Val, button2Col,RT, pb, buttonAction) {
    var code = document.getElementById('game-userName').innerHTML;
    var pb = pb.innerHTML;
    const dateien = {
        code,
        button1Val,
        button1Col,
        button2Val,
        button2Col,
        RT,
        pb,
        action: buttonAction,
    };

    fetch(`http://localhost:3000/Custard/data/${code}`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(dateien)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Nope -- Network response was not ok');
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

Client-Side package.json snippet:

  "name": "client",
  "version": "0.1.0",
  "private": false,
  "proxy": "http://localhost:3000",
  "type": "module",

Thanks in advance!

I tried changing the proxy settings for the client package.json, I also tried different routes, all to no avail.

Rotate text in docx js table

I want to rotate text so that it is written vertically in a table cell instead of horizintally. In Word you can achieve this by using these settings:

text direction in Word

How can I achieve it using docx js? I’ve searched documentation and their github repository and couldn’t find a solution. I’ve tried to use this property of a TableCell:

textDirection: TextDirection.LEFT_TO_RIGHT_TOP_TO_BOTTOM,

which I found in this demo but it didn’t give any result and I assume it’s not meant to rotate a text.

Part of my code:

import { TableRow, TableCell, Paragraph, TextRun, AlignmentType, VerticalAlign, TextDirection, HeightRule, convertMillimetersToTwip, WidthType } from "docx";
...
new TableCell({
                children: [
                    new Paragraph({
                        children: [
                            new TextRun({
                                text: `Some text here`,
                                size: 28,
                            })
                        ],
                        alignment: AlignmentType.CENTER,
                    })
                ],
                textDirection: TextDirection.LEFT_TO_RIGHT_TOP_TO_BOTTOM,
                width: {
                    size: convertMillimetersToTwip(10),
                    type: WidthType.DXA,
                },
                rowSpan: 16,
                verticalAlign: VerticalAlign.CENTER,
            }),