Why is this Javascript code running twice?

In vanilla JS, I want to take a value and append it to the href value of a link, but for reasons I can’t understand the value is being added twice.

My HTML is:

<a href="some-path/some-page" class="js-btn">Click me</a>

My Javascript is:

var refCode = "1234";

var href1 = document.querySelector(".js-btn").href;

document.querySelector(".js-btn").href = href1 + "?referral_code=" + refCode;

console.log(href1);

The expected result is:

<a href="some-path/some-page?referral_code=1234" class="js-btn">Click me</a>

but the actual result is:

<a href="some-path/some-page?referral_code=1234?referral_code=1234" class="js-btn">Click me</a>

Of course, I’ve checked to see if the script is appearing twice, but it’s not.

Would anyone know why this is?

I want to execute a command only if an interval is running

I’m making a command that sends a specific message every 1.5 seconds. I have also made a command to stop the interval. It works as i expected. But if the interval is not running and someone executes the stop command, the whole bot crashes. I want to stop that
Here’s the code –

else if (command === prefix + "spam" && args[0] !== undefined) {
        message.reply("Quick tip: Use `stopspam` command to stop this")
        spamInterval = setInterval(() => {
          message.channel.send(`${args.slice(0).join(" ")}`)
        }, 1500)
      }
    else if (command === prefix + "stopspam") {
        clearInterval(spamInterval);
        message.reply("Stopped the spamming. Hope it created some chaos :skull:")
    }

Music player in react native

Which is a best way to fetch the all my audio files which store in my local device storage and use in a my react native offline music player app . Or suggest me library which help me to archive this task

Error occured in react.production.min.js after deploying react app to the aws amplify

I’ve made complex react app but after deploying it on aws amplify i’ve got these errors, i don’t know why i got these errors, on local it works perfectly
here is the error log

Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at j (react.production.min.js:18)
at t.useContext (react.production.min.js:22)
at oe (hooks.js:18)
at Lu (Body.js:18)
at li (react-dom.production.min.js:157)
at Gl (react-dom.production.min.js:267)
at Is (react-dom.production.min.js:250)
at Bs (react-dom.production.min.js:250)
at Ms (react-dom.production.min.js:250)
at bs (react-dom.production.min.js:243)
ul @ react-dom.production.min.js:216

Uncaught Error: Minified React error #321; visit 
https://reactjs.org/docs/error-decoder.html? react-dom.production.min.js:260 
invariant=321 for the full message or use 
the non-minified dev environment for full errors and additional helpful warnings.
at j (react.production.min.js:18)
at t.useContext (react.production.min.js:22)
at oe (hooks.js:18)
at Lu (Body.js:18)
at li (react-dom.production.min.js:157)
at Gl (react-dom.production.min.js:267)
at Is (react-dom.production.min.js:250)
at Bs (react-dom.production.min.js:250)
at Ms (react-dom.production.min.js:250)
at bs (react-dom.production.min.js:243)

if you know any solution or way to solve these kind of errors please answer it here! thanks 🙂

JavaScript – Balance an Unbalanced Power Load

The array below contains a list of numbers that represent power load. The while loop, loops through the array and gets the sum of the array. The sum is then passed into the balance_load function so it can divide it into 3 parts such that the maximum and minimum value are as minimum as possible. What I would like to do next is write an algorithm that will distribute the available numbers(load) in the array to x, y and z such that the total values in x, y and z are very close to eachother and the sum of all three equal the sum of the entire array which in the example below is 909. The objective is to make the load as balanced as possible.

**GET SUM OF THE ARRAY AND DIVIDE IN THREE PARTS**
let x = 0;
let y = 0;
let z = 0;


function balance_load(x, n){
  let balanced_load = []
  if(x < n){
    balanced_load.push('-1')
  }else if(x % n === 0){
    for(let i=0; i<n; i++){
      balanced_load.push((x/n))
    }
  }else{
    let smallest_value = Math.floor(x/n);
    let smallest_value_count = n - (x % n)

    for(let i=0; i<n;i++){
      if(i >= smallest_value_count){
        balanced_load.push((smallest_value + 1))
      }else{
        balanced_load.push(smallest_value)
      }
    }
  }

  return balanced_load
}



let total = 0;


let array = [50,50,25,167,167,50,25,50,75,75,25,50,25,50,25]


for(let i of array){
  total += i
}
let balance = balance_load(total,3)

console.log(balance)
**EXAMPLE OF THE TYPE OF OUTPUT I AM LOOKING FOR AFTER GETTING SUM OF THE ARRAY AND DIVIDING IT BY THREE**

//x=317 (50 + 167 + 50 + 50)
//y=292 (167 + 75 +25 + 25)
//z=300 (50 + 25 + 50 + 25 + 75 + 50 + 25)
//x + y + z = 909//which is  the total

Javascript array values take from JSON file

I need to take this catWomen, catMen (Like other arrays) child data array values from a JSON file which is stored in my react app frontend. This catWomen, catMen like arrays data take for a drop-down in website homepage, I just only need to get these arrays child data (ex: catWomen array’s cloths’ child data item2, item 8) from separate JSON file

/* eslint-disable react/jsx-pascal-case */
import React, { Fragment, useState, useRef } from "react";
import { Col, Row } from "antd";
import { useNavigate } from "react-router-dom";
import { Menu, Transition } from "@headlessui/react";
import * as Icons from "../../assets/svg/mobile-icons";
import * as Icons2 from "../../assets/svg/icon";

import data01 from  './CategoriesData.json'

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}


const catWomen = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.frock01 />,
    childs: ["item2", "item8"],
  },
  {
    id: 3,
    name: "Shoes",
    icon: <Icons2.shoes06 />,
    childs: ["item3", "item7"],
  },
  { id: 4, name: "Bags", icon: <Icons2.purse01 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.bag05 />,
    childs: ["item5", "item2"],
  },
  { id: 6, name: "Beauty", icon: <Icons2.hat02 />, childs: ["item6", "item4"] },
];


const catMen = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.shirt1 />,
    childs: ["item2", "item8"],
  },
  { id: 3, name: "Shoes", icon: <Icons2.shoes1 />, childs: ["item3", "item7"] },
  { id: 4, name: "Bags", icon: <Icons2.bag05 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.purse02 />,
    childs: ["item5", "item2"],
  },
  { id: 6, name: "Grooming", icon: <Icons2.hat />, childs: ["item6", "item4"] },
];

const catKids = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.shirt1 />,
    childs: ["item2", "item8"],
  },
  {
    id: 3,
    name: "Shoes",
    icon: <Icons2.shoes05 />,
    childs: ["item3", "item7"],
  },
  { id: 4, name: "Bags", icon: <Icons2.bag05 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.bow />,
    childs: ["item5", "item2"],
  },
  {
    id: 6,
    name: "Grooming",
    icon: <Icons2.hat03 />,
    childs: ["item6", "item4"],
  },
];

const Categories = () => {
  const navigate = useNavigate();

  function SubCategories(props) {
    return (
      <Transition
        enter="transition ease-out duration-100"
        enterFrom="transform opacity-0 scale-95"
        enterTo="transform opacity-100 scale-100"
        leave="transition ease-in duration-75"
        leaveFrom="transform opacity-100 scale-100"
        leaveTo="transform opacity-0 scale-95"
      >
        <Menu.Items className="origin-top absolute w-auto rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100 focus:outline-none">
          <div className="py-1 flex">{props.children}</div>
        </Menu.Items>
      </Transition>
    );
  }

  function DropDownItem(props) {
    const items = props.data.map((item) => (
      <Menu.Item key={item.id.toString()}>
        {({ active }) => (
          <div
            onMouseOver={() => setChild(item.id)}
            onClick={() => {
              item.id === 1
                ? navigate(`/allproducts?mainProductCategory=${props.parent}`)
                : navigate(
                    `/allproducts?mainProductCategory=${props.parent}&category=${item.name}`
                  );
            }}
            className={classNames(
              active ? "bg-gray-100 text-gray-900" : "text-gray-700",
              "grid grid-cols-8 block px-4 py-2 text-xs"
            )}
          >
            <div className="col-span-7">{item.name}</div>
            <div className="col-span-1">{item.icon}</div>
          </div>
        )}
      </Menu.Item>
    ));
    return (
      <>
        <div className="border-r border-gray-300 w-40 text-sm">{items}</div>
      </>
    );
  }

  const [child, setChild] = useState(1);

  function LoadChilds(props) {
    const childs = props.data[props.child - 1];
    const subItems = childs.childs.map((item) => (
      <Menu.Item key={item.toString()}>
        {({ active }) => (
          <div
            onClick={() => navigate(`/allproducts?mainProductCategory=${props.parent}&category=${childs.name}&subCategory=${item}`)}
            className={classNames(
              active ? "bg-gray-100 text-gray-900" : "text-gray-700",
              "block px-4 py-2 text-sm"
            )}
          >
            {item}
          </div>
        )}
      </Menu.Item>
    ));
    return <div className="w-56">{subItems}</div>;
  }

  const dropdownRef = useRef();

  return (
    <Row className="bg-white w-full" style={{ position: "fixed", border: 0 }}>
      <Col offset={2}>
        <div className="flex w-full gap-6 text-xs cursor-pointer mt-0.5">
          <Menu as="div">
            <div
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
              onClick={() => navigate(`/allproducts`)}
            >
              <p>Shop</p>
            </div>
          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>Women</p>
            </Menu.Button>
            <div ref={dropdownRef}>
              <SubCategories>
                <DropDownItem data={catWomen} parent="Women" />
                <LoadChilds child={child} data={catWomen} parent="Women" />
              </SubCategories>
            </div>
          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>Men</p>
            </Menu.Button>
            <div ref={dropdownRef}>
              <SubCategories>
                <DropDownItem data={catMen} parent="Men" />
                <LoadChilds child={child} data={catMen} parent="Men" />
              </SubCategories>
            </div>
          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>Kids</p>
            </Menu.Button>
            <div ref={dropdownRef}>
              <SubCategories>
                <DropDownItem data={catKids} parent="Kids" />
                <LoadChilds child={child} data={catKids} parent="Kids" />
              </SubCategories>
            </div>
          </Menu>

          <Menu as="div">
            <div
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>About</p>
            </div>
          </Menu>
        </div>
      </Col>
    </Row>
  );
};

export default Categories;

Unsure why my function won’t execute the discount section of the code, but runs the other half? [duplicate]

below I have written my script code and html portion for a section of my code that I feel may contain an error that my eyes are not catching. In this code, there is supposed to be a discount section, if a user clicks ‘yes’ instead of ‘no’, a 10% discount is applied, the ‘no’ part runs fine, but the ‘yes’ part doesn’t. I have already checked for syntax and grammatical errors but feel that I may be skimming over them, or my code might be missing an important piece. I have put my code down below, both the script and html portions. If anyone has any insight or spots something, please let me know! Thanks!

var membersDiscount;
    membersDiscount = document.getElementById("radFirstChoice").value;
    if (radFirstChoice == "Yes") {
        membersDiscount = (results * .10);
    }
    else {
        membersDiscount = 0;
    }

    var truePrice; 
    truePrice = results - membersDiscount;
    truePrice = parseFloat(truePrice);
    truePrice = truePrice.toFixed(2);
   
<p><label>Are you a member of our frequent shipper club?</label></p>
<p><label for="radFirstChoice">Yes</label>
     <input type="radio"  id="radFirstChoice"  name="userInformation"></p> 
<p><label for="radSecondChoice">No</label>
    <input type="radio"  id="radSecondChoice" name="userInformation"></p>

I got a Frontend of a website but can’t get a bankend or admin for it

I am an IT student and a novice in the world of Development On WEBSITE and APP
I am ready to learn
I extracted a particular website(https://blockchain-poly.uk) with HTTRACK Software, because the front page suit what i needed, But after extracting it, i find only the front page file and i am really confused now cos it seems so difficult for me to get an admin dash board and client dashboard…

Please Help Me
Its Really Urgent.
Yours Sincere.

I want to convert jquery code to vanilla code [duplicate]

my english is not very good

jquery 1.5.2 is required for this code. I wonder if you could change it to vanilla, which doesn’t require a library? I don’t want to download 30 kilobytes of file for so little code. thanks in advance

$(function() {
   $('a').click(function() {
       $(this).addClass('active');
   });
});

Populating the HTML page with the JSON data in Angular

I have the following JSON data but would like to implement the HTML page such that it shows the parent as the header and all the children under the same parent under the content and then follow on by the second parent as the header and all the children under the second parent under the content. How would I be able to do so? An example would be like the following.

Sample 1

Product 1 – Test Product 1

Product 2 – Test Product 2

Sample 2

Product 1 – Test Product 1

sampleList": [
        {
    "parent": "Sample 1",
    "children": [
        {
            "product": "Product 1",
            "name": "Test Product 1",
        }
    ],
    "parent": "Sample 1",
    "children": [
        {
            "product": "Product 2",
            "name": "Test Product 2",
        }
    ],
    "parent": "Sample 2",
    "children": [
        {
            "product": "Product 1",
            "name": "Test Product 1",
        }
    ]
}
]

Having trouble with a hierarchical WordPress sidebar menu. The script always appends the slug so you can’t navigate back up the hierarchy

The menu uses a toggle to drop down child pages. It’s then possible to navigate to a child page, but getting back to the parent page, or a different parent page is impossible, since each time, the slug is appended to the URL.

For example:
https://rogera25.sg-host.com/managing-epilepsy/women-and-epilepsy/
Within the Women and Epilepsy segment I can reach child pages like:
https://rogera25.sg-host.com/managing-epilepsy/women-and-epilepsy/pregnancy-planning/
But I can’t then go back to a different section like ‘Living With Epilepsy’ because this happens, resulting in a 404:
https://rogera25.sg-host.com/managing-epilepsy/women-and-epilepsy/pregnancy-planning/living-with-epilepsy

Can anyone help? Thanks so much for taking the time to read this!

<aside class="sub-menu col mx-auto">

    <ul class="nav flex-column mx-2 menu">

        {% set siblings = post_query({ 
        'post_type': 'page',
        'post_parent': ancestor,
        'orderby': 'menu_order',
        'order': 'ASC'
    }) %}

    <a class="nav-side-title {% if fn('is_page', ancestor.slug) %}active{% endif %}" href="{{ ancestor.link }}">
    
    <h4>{{ ancestor_name }}</h4></a>

    {% for sibling in siblings %}

        {% if sibling.children %}

            <div class="top mx-2 d-flex align-items-baseline">

                <li class="nav-item top-parent has-child collapsed" href="#{{ sibling.slug }}" data-toggle="collapse" aria-controls="{{ sibling.title }}"></li>
                <a class="nav-link {% if fn('is_page', sibling.slug) %}active{% endif %}" href="{{ sibling.slug }}">{{ sibling.title }}</a>
            </div>

            <ul id="{{ sibling.slug }}" class="collapse child-menu" aria-labelledby="{{ sibling.title }}">

                {% for subpage in sibling.children %}

                   {% if subpage.post_type == "page" %}

                    {% if subpage.children %}
                        <div class="mx-3 d-flex align-items-baseline">
                           <li class="nav-item middle-parent has-child collapsed" href="#{{ subpage.slug }}" data-toggle="collapse" aria-controls="{{ subpage.title }}"></li>
                                <a class="nav-link subpage{% if fn('is_page', subpage.slug) %} active{% endif %}" href="{{ subpage.link }}">{{ subpage.title }}</a>

                           </div>
                           <ul id="{{ subpage.slug }}" class="grandchild-menu collapse" aria-labelledby="{{ subpage.title }}">

                            {% for subpage_2 in subpage.children %}
                               {% if subpage_2.post_type == "page" %}


                                <li class="nav-item bottom">
                                    <a class="nav-link subpage{% if fn('is_page', subpage_2.slug) %} active{% endif %}" href="{{ subpage_2.link }}"> {{ subpage_2.title }}</a>
                                </li>



                                    {% endif %}
                                {% endfor %}<!--subpage_2-->
                            </ul>
                        {% else %}<!--subpage.children-->

                            <li class="nav-item middle">
                                <a class="nav-link subpage{% if fn('is_page', subpage.slug) %} active{% endif %}" href="{{ subpage.link }}">{{ subpage.title }}</a>
                            </li>

                        {% endif %} <!--subpage.children-->

                    {% else %}
                            <li class="nav-item middle">
                                <a class="nav-link subpage{% if fn('is_page', subpage.slug) %} active{% endif %}" href="{{ subpage.link }}">{{ subpage.title }}</a>
                            </li>
                        
                    {% endif %}<!--subpage.children page-->

                {% endfor %} <!--subpage-->

            </ul>



        {% else %} <!--sibling.children-->

            <li class="nav-item top">
                <a class="nav-link {% if fn('is_page', sibling.slug) %} active{% endif %}" href="{{ sibling.link }}">{{ sibling.title }}</a>
            </li>


        {% endif %}<!--sibling.children-->

    {% endfor %} <!--sibling-->

    </ul>

</aside>

Javascript method setTimeout() does not work well in Safari browser

I try to develop javascript codes that can give users a warning when the server too long to response the html form submitted. My codes works well in Chrome and Firefox desktop browser, but not in Safari desktop browser.
How to make this works in Safari ? Here are my codes:

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8"/>
   <script type="text/javascript">
      function handleTimeout() {
         document.getElementById("retryButton").disabled = false;
         document.getElementById("message").innerHTML = "Your card's bank 3DS OTP page might be having issue. Please "Tap to retry".";
      }
      function retry() {
         setTimeout(handleTimeout, 5000);
         submitForm();
      }
      function submitForm() {
         return new Promise(function(resolve, reject) {
            document.getElementById('requestForm').submit();
            resolve("done");
         });
      }
      function start() {
         document.getElementById("retryButton").disabled = true;
         setTimeout(handleTimeout, 5000);
         submitForm();
      }
      window.addEventListener('load', (event) => {
         start();
      });
   </script>
</head>
<body>
<form id="requestForm" method="post" action="http://localhost:10877/auth/pareq">
   <input type="hidden" name="PaReq" value="eyJ2ZXJzaW9uIjoiMS4wLjIiLC"/>
   <input type="hidden" name="uuid" value="ac456037-995b-4778-bba5-df614db7ebaa"/>
   <input type="hidden" name="Status" value="Y"/>
</form>
<div id="message">Processing OTP</div>
<p>Tap the button below to Retry</p><br/>
<button id="retryButton" onclick="retry();">Tap to retry</button>
</body>
</html>

Function handleTimeout() is not working in Safari but works well in Chrome and Firefox browser.
How to make function handleTimeout() works well in Safari?

location.href load on the current page/previous url

i have the following jquery for onclick code :

function find(){
$.ajax({
    type: "post",
    url: link + 'register/data',
    data: {},
    success: function () {
        window.location.href= "mycontroller/myfunction"
    }
});

}

i want to make the url stays on mycontroller/myfunction everytime they click the button, i tried substring lastindexof but it keeps adding more url everytime i click the button, how do i make the button stays on that whenever i click it?
thanks in advance

I’m trying to figure out if I’m having trouble understanding the question or the code itself. What do you think? [closed]

I’m currently learning JavaScript on freecodecamp and just had to stop to ask.
When I look at the code (finished layout of a function) it makes sense of what it does.
However, when I read the directions, I simply don’t get it or can’t even picture the finished code. I tend to get stuck on just what it’s asking for me to do. I do spend good amount re-reading everything over and over, but at a point I do google to see the finished product just to understand the requirements for the task.

is it FCC wording the problem? What do you think is my problem?
I get more confused on platform wordings than the actual code.
Block of code I can break it down but with directions it gets confusing of what they want.
Should I just move on? at what point is spending too much time on a question?

Thank you,
D.R.