toggle visibility of 2 divs with 2 buttons independently

I create two divs (audiodescription-text and options-wrapper). I want to toggle their visibility independently. In other words, the visibility of one div doesn’t affect another one’s visibility. That’s why I created 2 buttons, one for each div.

However, with the following code, when you click in any button, the same div is hidden or shown.

What am I doing wrong? Can someone fix the code for me?

/* Inserir aqui script para exibir ou ocultar o menu de seleção de cores */
var div = document.getElementById('audiodescription-text');
var display = 1;

function showHidenButtonAudiodescription() {
  if (display == 0) {
    div.style.display = 'none';
    display = 1;
    document.querySelector("button_audiodescription").innerHTML = "Exibir audiodescrição";
  } else {
    div.style.display = 'inherit';
    display = 0;
    document.querySelector("button_audiodescription").innerHTML = "Ocultar audiodescrição";
  }
}

/* Inserir aqui script para exibir ou ocultar o menu de seleção de cores */
var div = document.getElementById('options-wrapper');
var display = 1;

function showHidenButtonModel() {
  if (display == 0) {
    div.style.display = 'none';
    display = 1;
    document.querySelector("button_model").innerHTML = "Exibir audiodescrição";
  } else {
    div.style.display = 'inherit';
    display = 0;
    document.querySelector("button_model").innerHTML = "Ocultar audiodescrição";
  }
}
var config = { /* Insira aqui a URL do modelo tridimensional hospedado no Sketchfab que será carregado. Insira aqui os materiais, os nomes e as cores de cada estrutura. Basicamente, este é o trecho do código que deve ser alterado para se adaptar a cada modelo tridimensional */

  "model": "066fa44695014754ad13f0e69ddda1c3",
  "params": {
    "camera": 0,
    "autoplay": 0,
    "preload": 1,
    "ui_controls": 0,
    "ui_infos": 0,
    "ui_watermark": 0
  },
  "config": [{
      "name": "01. Parede Celular",
      "type": "color",
      "material": "Parede",
      "default": "#b27e00",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688313518707
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688313518707
        },
        {
          "name": "Branco",
          "color": "#ffffff",
          "id": 1688313518707
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688313518707
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688313518707
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688313518707
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688313518707
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688313518707
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688313518707
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688313518707
        }
      ]
    },
    {
      "name": "02. Cílios",
      "type": "color",
      "material": "Cilios",
      "default": "#a9821b",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688313690276
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688313690276
        },
        {
          "name": "Branco",
          "color": "#ffffff",
          "id": 1688313690276
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688313690276
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688313690276
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688313690276
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688313690276
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688313690276
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688313690276
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688313690276
        }
      ]
    },
    {
      "name": "03. Membrana Plasmática",
      "type": "color",
      "material": "Membrana",
      "default": "#e7710c",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688313830703
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688313830703
        },
        {
          "name": "Branco",
          "color": "#ffffff",
          "id": 1688313830703
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688313830703
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688313830703
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688313830703
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688313830703
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688313830703
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688313830703
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688313830703
        }
      ]
    },
    {
      "name": "04.Citoplasma",
      "type": "color",
      "material": "Citoplasma",
      "default": "#e7e7e7",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688313956926
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688313956926
        },
        {
          "name": "Branco",
          "color": "#ffffff",
          "id": 1688313956926
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688313956926
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688313956926
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688313956926
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688313956926
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688313956926
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688313956926
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688313956926
        }
      ]
    },
    {
      "name": "05. Ribossomos",
      "type": "color",
      "material": "Ribossomos",
      "default": "#e300e7",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688314141902
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688314141902
        },
        {
          "name": "Branco",
          "color": "#FFFFFF",
          "id": 1688314141902
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688314141902
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688314141902
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688314141902
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688314141902
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688314141902
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688314141902
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688314141902
        }
      ]
    },
    {
      "name": "06. Material Genético",
      "type": "color",
      "material": "Material Genetico",
      "default": "#00c8e7",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688314249006
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688314249006
        },
        {
          "name": "Branco",
          "color": "#FFFFFF",
          "id": 1688314249006
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688314249006
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688314249006
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688314249006
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688314249006
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688314249006
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688314249006
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688314249006
        }
      ]
    },
    {
      "name": "07. Plasmídio",
      "type": "color",
      "material": "Plasmidio",
      "default": "#0011e7",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688314352195
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688314352195
        },
        {
          "name": "Branco",
          "color": "#FFFFFF",
          "id": 1688314352195
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688314352195
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688314352195
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688314352195
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688314352195
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688314352195
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688314352195
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688314352195
        }
      ]
    },
    {
      "name": "08. Flagelo",
      "type": "color",
      "material": "Flagelo",
      "default": "#834520",
      "options": [{
          "name": "Preto",
          "color": "#000000",
          "id": 1688314449619
        },
        {
          "name": "Cinza",
          "color": "#b3b3b3",
          "id": 1688314449619
        },
        {
          "name": "Branco",
          "color": "#FFFFFF",
          "id": 1688314449619
        },
        {
          "name": "Vermelho",
          "color": "#db2828",
          "id": 1688314449619
        },
        {
          "name": "Laranja",
          "color": "#f2711c",
          "id": 1688314449619
        },
        {
          "name": "Amarelo",
          "color": "#fbbd08",
          "id": 1688314449619
        },
        {
          "name": "Verde",
          "color": "#21ba45",
          "id": 1688314449619
        },
        {
          "name": "Azul",
          "color": "#2185d0",
          "id": 1688314449619
        },
        {
          "name": "Roxo",
          "color": "#a333c8",
          "id": 1688314449619
        },
        {
          "name": "Rosa",
          "color": "#e03997",
          "id": 1688314449619 /* Aqui termina o conteúdo personalizado de cada modelo tridimensional */
        }
      ]
    }
  ].map((e) => {
    return {
      ...e,
      options: e.options.map((f) => ({
        color: f.color,
        id: f.id,
      })),
    };
  })
};
var iframeEl = document.getElementById('api-frame');
var optionsEl = document.querySelector('.options');
var configurator = new SketchfabConfigurator.Configurator(iframeEl, optionsEl, config);
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  font-family: 'Quicksand', sans-serif;
  /* Altere aqui a fonte e o tamanho da fonte */
  box-sizing: border-box;
  font-size: 12px;
}

#audiodescription-instructions {
  width: 100%;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  padding-top: 10px;
}

button_audiodescription {
  /* Altere aqui as configurações visuais do botão em estado normal*/
  padding: 6px 24px;
  text-align: center;
  font-family: 'Quicksand', sans-serif;
  color: #0d6efd;
  font-size: 14px;
  border: solid;
  border-width: 1px;
  border-color: #0d6efd;
  border-radius: 8px;
  cursor: pointer;
}

button_audiodescription:hover {
  /* Altere aqui as configurações visuais do botão em estado normal*/
  color: white;
  background-color: #0d6efd;
}

#audiodescription-text {
  /* Criar aqui uma classe para conter a interface de seleção de cores */
  margin: 20px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 15px;
  border-width: 1px;
  border-style: solid;
  border-radius: 8px;
  font-weight: bold;
  font-size: 16px;
  letter-spacing: 0.12px;
  border-width: 1px;
  border-style: solid;
  border-radius: 8px;
  font-weight: bold;
  font-size: 16px;
}

.sketchfab-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 900px;
  overflow: hidden;
  /* Oculte aqui a barra de rolagem */
}

iframe {
  width: 100%;
  height: 70%;
  margin-bottom: 0px;
  /* Oculte aqui a borda */
  border: none;
}

#model-instructions {
  /* Criar aqui uma classe para exibir texto com instrução de seleção de cores. Este será o elemento-pai */
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  padding-top: 10px;
}

button_model {
  /* Altere aqui as configurações visuais do botão em estado normal*/
  padding: 6px 24px;
  text-align: center;
  font-family: 'Quicksand', sans-serif;
  color: #0d6efd;
  font-size: 14px;
  border: solid;
  border-width: 1px;
  border-color: #0d6efd;
  border-radius: 8px;
  cursor: pointer;
}

button_model:hover {
  /* Altere aqui as configurações visuais do botão em estado normal*/
  color: white;
  background-color: #0d6efd;
}

#options-wrapper {
  /* Criar aqui uma classe para conter a interface de seleção de cores */
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 20px
}

.options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0 50px;
}

.option {
  display: flex;
  flex-direction: column;
  gap: 4px;
  /* Altere aqui o espaçamento entre o nome da estrutura e os quadrados de cores. O espaçamento original é 8px */
  padding: 12px 0;
  /* Altere aqui o espaçamento geral entre as linhas. O espaçamento original é 16px */
}

.color {
  display: flex;
  align-items: center;
  padding: 1px 0;
  /* Altere aqui o espaçamento entre as linhas no menu de seleção de cores. O espaçamento original é 4px */
}

.color input[type="radio"] {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.option__control {
  display: flex;
  /* Altere aqui o espaçamento horizontal entre os quadrados de cores. O espaçamento original é 8px */
  gap: 3px;
}

.color__swatch {
  display: inline-block;
  width: 24px;
  height: 24px;
  /* Altere aqui a curvatura da borda do quadrado de cores. A curvatura orginal é 8px */
  border-radius: 4px;
  /* Altere aqui o tamanho do quadrado de cores. O tamanho original é 25px */
  width: 20px;
  height: 20px;
  border: 1px solid rgba(0, 0, 0, 0.5);
  margin-right: 4px;
}

.color input:checked+.color__swatch {
  /* Altere aqui a borda da cor atualmente atribuída a determinada estrutura. A cor original é #000 */
  box-shadow: 0 0 0 2px #fff;
}

.color:hover .color__swatch {
  box-shadow: 0 0 0 2px #999;
}

.texture {
  display: block;
  position: relative;
  margin-bottom: 10px;
}

.texture input[type="radio"] {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.texture__preview {
  display: block;
}

.texture__preview img {
  display: block;
  max-width: 100%;
  height: auto;
}

.texture input:checked+.texture__preview>img {
  box-shadow: 0 0 0 2px #000;
}

.texture__name {
  display: block;
  margin-top: 4px;
}


/* Aqui termina o conteúdo do arquvo styles.css */
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sketchfab Configurator</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<!-- Insira aqui a fonte não suportada pelo css -->
<link rel="stylesheet" href="./styles.css">
<script type="text/javascript" src="./assets/js/sketchfab-viewer-1.3.2.js"></script>
<script type="text/javascript" src="./assets/js/SketchfabConfigurator-1.0.6.js">
</script>

<body>
  <div id="audiodescription-instructions">
    <button_audiodescription id="button_audiodescription" onclick="showHidenButtonAudiodescription()">Exibir audiodescrição</button_audiodescription>
    <div style="display:none" ; id="audiodescription-text">
      <p>
        [AUDIODESCRIÇÃO: representação tridimensional colorida de uma célula eucariótica seccionada, ou seja, cortada ao meio para mostrar as principais estruturas constituintes.<br><br> Para facilitar a compreensão e considerando a posição inicial em
        que o modelo tridimensional é carregado, a apresentação e a descrição das estruturas são feitas da esquerda para a direita e de fora para dentro, ou seja, as mais externas primeiro e em seguida as mais internas. Inicialmente são descritas as estruturas
        em primeiro plano, para depois serem descritas as estruturas em planos mais ao fundo.<br><br> A célula eucariótica apresenta formato irregular, mais próximo do arredondado, sendo delimitada pela membrana plasmática com superfície é lisa. Internamente,
        apresenta citoplasma e organelas.<br><br> Em uma célula real as organelas não possuem posição fixa, podendo variar de localização. Neste modelo tridimensional, em primeiro plano e à esquerda, encontram-se lisossomos, pequenas organelas de formato
        arredondado. Mais à direita está o Complexo de Golgi formado por sacos achatados e empilhados, interconectados por vesículas. Um pouco mais atrás, e à esquerda do lisossomo, encontra-se um endossomo, com formato arredondado similar aos lisossomos,
        porém de maior diâmetro. Segue-se o retículo endoplasmático rugoso, rede de cisternas e túbulos interconectados que possuem ribossomos aderidos à sua face externa, os quais estão representados como pequenos grânulos arredondados. À direita do
        retículo endoplasmático rugoso, está uma mitocôndria, de formato alongado e cilíndrico e com cristas mitocondriais de formato ondulado em seu interior. Logo atrás está um proteassomo, estrutura pequena, de formato cilíndrico, cujas extremidades
        apresentam projeções. Do lado direito do proteassomo está o retículo endoplasmático liso, formado por tubos alongados interconectados. Do lado direito do retículo endoplasmático liso está o núcleo, grande esfera com superfície lisa, dotada de
        poros circulares. O núcleo está seccionado de forma a mostrar, em sua região central, o nucléolo de formato também esférico. Finalmente, ao fundo, no extremo esquerdo, encontram-se dois centríolos de formato cilíndrico e dispostos perpendicularmente
        um ao outro, e no extremo direito, dois peroxissomos, organelas de formato circular semelhante ao endossomo e ao lisossomo.<br><br> FIM DA AUDIODESCRIÇÃO.]</p>
    </div>
  </div>

  <div class="sketchfab-container">
    <iframe src="" id="api-frame" allow="autoplay; fullscreen; xr-spatial-tracking" xr-spatial-tracking execution-while-out-of-viewport execution-while-not-rendered web-share allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" height="1000"
      width="100%"></iframe>

    <div id="model-instructions">
      <!-- Inserir aqui a classe e o texto com as instruções de seleção de cores -->
      <p>Selecione a cor desejada para cada estrutura:</p>
    </div>
    <!-- Inserir aqui o texto com as instruções -->
    <button_model id="button_model" onclick="showHidenButtonModel()">Exibir opções de cores</button_model>
    <!-- Inserir aqui botão para exibir ou ocultar o menu de seleção de cores -->
    <div style="display:none" ; id="options-wrapper">
      <!-- Altere aqui o estado inicial de exibição do menu de seleção de cores. display:none ocultará o elemento. display:inherit exibirá o elemento com os padrões de seu elemento-pai -->
      <div class="options" id="color-picker"></div>
    </div>
  </div>
</body>

Button for Woocommerce

I need help. I have a store on WooCommerce, I wrote a button, but it’s not working
Hi, I need help. I have a store on WooCommerce, I wrote a button, but it’s not working
Hi, I need help. I have a store on WooCommerce, I wrote a button, but it’s not working
Hi, I need help. I have a store on WooCommerce, I wrote a button, but it’s not working
Hi, I need help. I have a store on WooCommerce, I wrote a button, but it’s not working
Hi, I need help. I have a store on WooCommerce, I wrote a button, but it’s not working

<?php
/*
Plugin Name: WooCommerce Custom Sorting v1.3
Description: Adds a single sort button with a dropdown menu to sort products by price and name on the WooCommerce store page.
Version: 1.3
Author: blvckfamily
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


function add_custom_sorting_dropdown() {
    if ( is_shop() || is_product_category() ) { 
        echo '
        <div class="custom-sorting-dropdown">
            <button id="sortDropdownButton">Sorting <span>&#9662;</span></button>
            <div id="sortOptions" class="dropdown-content">
                <a href="#" data-sort="price">Price</a>
                <a href="#" data-sort="name">Name</a>
            </div>
        </div>';
    }
}
add_action( 'woocommerce_before_shop_loop', 'add_custom_sorting_dropdown', 10 );


function custom_sorting_dropdown_styles() {
    echo '
    <style>
    .custom-sorting-dropdown {
        position: relative;
        display: inline-block;
        margin-bottom: 20px;
    }
    
    #sortDropdownButton {
        background-color: #0071a1;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
    
    #sortDropdownButton:hover {
        background-color: #005a87;
    }

    .dropdown-content {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 160px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1;
    }
    
    .dropdown-content a {
        color: black;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
    }
    
    .dropdown-content a:hover {
        background-color: #f1f1f1;
    }
    
    .custom-sorting-dropdown:hover .dropdown-content {
        display: block;
    }
    </style>';
}
add_action( 'wp_head', 'custom_sorting_dropdown_styles' );


function custom_sorting_dropdown_scripts() {
    ?>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const sortDropdownButton = document.getElementById("sortDropdownButton");
        const dropdownContent = document.getElementById("sortOptions");

        if (!sortDropdownButton || !dropdownContent) {
            console.error("Dropdown button or content not found.");
            return;
        }

        document.querySelectorAll(".dropdown-content a").forEach(function(item) {
            item.addEventListener("click", function(event) {
                event.preventDefault();
                event.stopPropagation(); 

                let sortType = this.getAttribute("data-sort");

                if (!sortType) {
                    console.error("Sort type not found.");
                    return;
                }

                let sortOrder = "asc"; 

                let products = document.querySelectorAll('.woocommerce ul.products li.product');

                if (!products.length) {
                    console.error("No products found.");
                    return;
                }

                let productsArray = Array.prototype.slice.call(products, 0);

                if (sortType === "price") {
                    productsArray.sort(function(a, b) {
                        let priceAElement = a.querySelector('.woocommerce-Price-amount');
                        let priceBElement = b.querySelector('.woocommerce-Price-amount');

                        if (!priceAElement || !priceBElement) {
                            console.error("Price element not found in one of the products.");
                            return 0;
                        }

                        let priceA = parseFloat(priceAElement.innerText.replace(/[^0-9.-]+/g,""));
                        let priceB = parseFloat(priceBElement.innerText.replace(/[^0-9.-]+/g,""));
                        return sortOrder === "asc" ? priceA - priceB : priceB - priceA;
                    });
                } else if (sortType === "name") {
                    productsArray.sort(function(a, b) {
                        let nameAElement = a.querySelector('.woocommerce-loop-product__title');
                        let nameBElement = b.querySelector('.woocommerce-loop-product__title');

                        if (!nameAElement || !nameBElement) {
                            console.error("Product title element not found in one of the products.");
                            return 0;
                        }

                        let nameA = nameAElement.innerText.toLowerCase();
                        let nameB = nameBElement.innerText.toLowerCase();
                        if (nameA < nameB) return sortOrder === "asc" ? -1 : 1;
                        if (nameA > nameB) return sortOrder === "asc" ? 1 : -1;
                        return 0;
                    });
                }

                let parent = document.querySelector('.woocommerce ul.products');
                if (!parent) {
                    console.error("Products container not found.");
                    return;
                }

                
                parent.innerHTML = "";

                
                productsArray.forEach(function(product) {
                    parent.appendChild(product);
                });
            });
        });
    });
    </script>
    <?php
}

    
add_action( 'wp_footer', 'custom_sorting_dropdown_scripts' );

I just need help, actually.

how do I fetch a list of locations by zipcode

I have never worked in frontend so really a newbie to webdesign and javascript
Here is the problem I am trying to solve:
I want to design a webpage where the user inputs a zipcode and based on that the webpage fetches a list of locations. Similar to google maps functionality like “restaurants near 12345” or “gas stations near me”. I am using square space for the website, but I do know a bit of html and css. Also fluent in backend programming. Which frontend technologies should I look into?

Have just tried googling info.. looked up charity navigator, etc but nothing useful

Update css variable globally without javascript [duplicate]

I have the following styles:

html {
  --header-height: 80px;
  --announcement-bar-height: 40px;

  scroll-padding-top: calc(
    var(--header-height) + var(--announcement-bar-height) + 5px
  );

  body[data-scrolled] {
    --announcement-bar-height: 0px;
  }
}

The problem is that when I scroll the page and hence data-scrolled attribute is added to body, the --announcement-bar-height is not updated to 0px in scroll-padding-top in html and still 40px is used. How to fix that without javacript?

Error message on terminal when trying to create a React project

Im currently doing the Odin Project for web development (javascript path).
In the React Course, im learning to set up a project with React.
This is the page: https://www.theodinproject.com/lessons/node-path-react-new-setting-up-a-react-environment

The problem is that when i paste this command “npm create vite@latest my-first-react-app — –template react
” into the CLI, i get an error.

The error is this:
npm error Class extends value undefined is not a constructor or null
npm error A complete log of this run can be found in: C:UsersequipoAppDataLocalnpm-cache_logs2024-08-09T19_54_01_302Z-debug-0.log

Im using git Bash, and my pc cant run a virtual machine or WSL2.. so im stuck with this.

Anyone could help me? Thanks!!

PS: node and npm are up to date.

I really dont know what to do, i search on google and stack overflow posts but couldnt find the solution.. and in the Odin Porject they dont help windows users..

eventListener onload and “not defined” ID error in javascript

Problem:

the function “function1” start onload with many tasks and instead “function2” is awaiting to be load after some user event.

function2 create some elements with createElement and function1 even if has a listener inside seems to answer (as obvious) with a “not defined” error blocking everything.

is there a logic way to solve this procedural mistake/error=

Why does Discord refuse to embed my website?

My website embeds perfectly as expected everywhere I’ve tried except Discord, for some reason it refuses to embed no matter what I try and I cannot figure out why, I’ve tried:

  • remaking my tags entirely;
  • stripping my backend of all security;
  • completely rebuilding my backend; and
  • allowing Discord through every bit of security I have.

The only times it has embedded properly were when I tried hosting one of my html files on tiiny.host and on GitHub Pages, so it must be something in my backend, but the only things I could think of possibly causing it were CORS, CSP, and Helmet, but even removing all 3 of them entirely didn’t work.

How to disable the touch elements in other parts of a display in the APL templates in an Alexa Skill?

So we have created an alexa skill which plays the latest news from WPI. But in viuals part when we click anywhere on the Alexa template in the Alexa Skill, it stops speaking so can someone please help us to disable the touch interactions on other parts of the display apart from the buttons.

We tried using touchwrapper and set state but it didn’t work.

sqlite3 callback gets run only after program is complete. Why then?

Disclaimer: I’m a 40 year veteran software developer: C, Java, lots of other stuff. Trying to do simple Object Oriented program in Javascript under Node.js. The threading and global memory management is baffling me.

I’m using a sqlite tutorial:
https://www.sqlitetutorial.net/sqlite-nodejs/query/

I’m running the query for all rows.
I have inserted this code into a Node.js file. I have wrapped that simple query in a function call. The function gets called, the query is submitted and the function returns to the calling code. However at that point I have code to save the results as a json file and the data is not there. When the program completes, THEN the callback from the query runs, but it is too late because the program saved no data and completed.

What do I need to insert to get it to actually run the query and call the callback?

Here is my ‘Book.js’ file:

    const fs = require('fs')
    // const Bible = require('./Bible.js');

    class Bible {
        constructor() {
            this.books = [];
            this.xrefs = [];
        }

        AddBook(book) {
            this.books.push(book);
            console.log('Book added: ' + book.name);
        }

        AddXref(xref) {
            this.xrefs.push(xref);
            console.log('Xref added: ' + xref);
        }
    }

    let theBible = new Bible();

    class Book {
        constructor(row) {
            this.ordinal     = row.order;
            this.name        = row.title_short;
            this.title       = row.title_full;
            this.category    = row.category;
            this.nChapters   = row.chapters;
        }
    }

    Book.load = function load( theBible ) {
        const sqlite3 = require('sqlite3').verbose();

    // open the database
        let db = new sqlite3.Database('./Data/bible-sqlite.db');

        let sql = `SELECT * FROM book_info`;

        db.all(sql, [], (err, rows) => {
            if (err) {
                throw err;
            }
            rows.forEach((row) => {
                book = new Book(row);
                theBible.AddBook(book);
                console.log(`Book[${book.ordinal}] ${book.name} loaded.`)
                console.log(book);
            });
        });

    // close the database connection
        db.close();
    }

    Book.saveAll = function saveAll(theBible) {

        if ( theBible != undefined && theBible.books != undefined) {
            console.log(theBible.books);

            // convert JSON object to a string
            const jsonData = JSON.stringify(theBible.books)

            // write JSON string to a file
            fs.writeFile('books.json', jsonData, err => {
                if (err) {
                    throw err
                }
                console.log('Books JSON data is saved.')
            })

        }

    }

    console.log('ready to load');
    Book.load(theBible);
    console.log("loaded, now to save it all.")
    Book.saveAll(theBible);
    console.log('done.');

    module.exports = Book;

Only after the final 5 lines of code are run and the program is done does the callback thread run.

What am I missing?

explained in the description. I was expecting the callback to deliver the data after the call to the Book.load() function (Method) returns, but it only happens after the whole program is ‘complete’.

why does it always executing the else block of code? [duplicate]

I was trying to make an isNaN() function that checks the user’s input if its a NaN or not, but it always skips the the first condition whatever the user’s input is.

function isNaN() {
    let value = prompt("enter value");

    if (typeof value === "number") {
    console.log("value is number");
    }else {
    console.log("NaN");
    }
} isNaN();

I made the program to checks the user’s input data type by typeof operator.

Issue with Svelte Configuration: Implicit “any” in TypeScript and Unrecognized Global SCSS Variables

I’m working on a SvelteKit project and encountering two main issues:

  1. Implicit “any” TypeScript Error:
    Even though I’m using JavaScript in my project, I’m seeing a TypeScript error Parameter '' implicitly has an 'any' type.ts(7006) in my code. It seems like TypeScript is checking for types in my JavaScript files, even though I haven’t explicitly used TypeScript in my project.

  2. Unrecognized Global SCSS Variables:
    I’m importing global SCSS variables using sveltePreprocess in my svelte.config.js file. However, when I try to use these variables in my .svelte files, I receive an error saying Error: Undefined variable. Despite this error, the code runs and functions correctly, but I’m concerned about why these variables are not being recognized during the build process.

Here’s my svelte.config.js:

import adapter from '@sveltejs/adapter-auto';
import { sveltePreprocess } from 'svelte-preprocess';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: [
        vitePreprocess(),
        sveltePreprocess({
            typescript: {
                compilerOptions: {
                    noImplicitAny: false
                }
            },
            scss: {
                prependData: `
                    @import 'src/assets/scss/global.scss';
                    @import 'src/assets/scss/variables.scss';
                `
            }
        })
    ],

    kit: {
        adapter: adapter()
    }
};

export default config;
  • For the TypeScript Issue:
    I attempted to suppress the implicit any errors by setting noImplicitAny: false in the TypeScript configuration within sveltePreprocess. However, the error still appears in my JavaScript files (and also <script> in .svelte files). I expected this configuration to prevent TypeScript from checking types in these files, but it doesn’t seem to be working as intended.

  • For the SCSS Variables Issue:
    I expected that by using prependData to import my global SCSS files (global.scss and variables.scss), the variables defined within them would be globally available in all my .svelte files. However, when I reference these variables, I get an Undefined variable error, even though the code still compiles and runs correctly. I’m not sure if the issue is related to how the SCSS is being processed or if there’s something else I’m missing in the configuration.

Any guidance or solutions to these issues would be greatly appreciated!

What does this.bind(‘string’) do?

Reading a piece of TypeScript (context Angular) came across a perplexing usage of the JavaScript bind function. Can anyone explain this pattern?

Example 1

const f = this.bind('astring');
return f ? f(someArgs) : someDefaultReturn;

The pattern in the first line is used a number of times here.

Per the docs, the usage for bind says it’s called on a function and is passed an object like so:

Example 2

const f = someFunc.bind(someObject);

Where f is a function that calls someFunc and makes its ‘this’ context equal to someObject when f is called, which all makes sense.

But when the code in the pattern in example 1 at the top is run, someFunc (‘this’) turns out to be an object (actually an instance of a class which has ‘bind’ so yes, it may technically be a function) and someObject (‘astring’) is a primitive not an object (yes, I know all primatives are actually wrapped in objects). It’s completely thrown me.

What is this code doing and how?

Rendering images using JS Canvas with partially transparent pixels after applying an opacity filter slows down my program significantly

I am making a small game using JavaScript, and to draw stuff I am using Canvas2D. The performance of the game is great, and it runs 60fps consistently. Or at least it did until I added a specific texture that contains pixels with partial opacity. I need to make those textures fade away, so I use ctx.filter = "opacity(n%)" where n controls the opacity. When I do this on a fully solid texture (a zombie in my case) no issues occur. But when I attempt to use the same filter on a texture with some translucent pixels, the game drops FPS. Here is the code I use:

ctx.save();
//deathAnim is a variable used for animating the fade out.
if(this.deathAnim) {
    ctx.filter = "brightness(0) opacity(" + (1 - this.deathAnim) + ")"
}
this.drawShadow(); //this draws the "problematic" translucent texture. When I remove this the game runs fine.
this.drawBody(); //this draws the zombie texture, and no issues here regarding lag.
ctx.restore();

I haven’t tried much yet, but If I remove that filter entirely, the game runs fine. Anyone know a workaround I can use, or something to fix the lag?

EDIT: After some further testing, I found out that this filter also affects the zombie texture. Whenever I apply it, the game lags out.

a function to reload, refresh or update the div content (part of page, not whole page) when buttom clicked using javascript ajax without jquery?

this code is in function.php

<?php
# get company function
function get_company($db)
{
    $company_id = $_GET['id'];
    $company = $db->prepare("SELECT * FROM companies WHERE company_id = :company_id");
    $company->execute(['company_id' => $company_id]);
    $company = $company->fetch();
    return $company;
}
?>

this code is in index.php (the main file or home page)

<?php
$companies = get_companies($db);
?>
<article id="article">
            <?php if ($companies->rowCount() > 0) { ?>
                <!-- list of all companies -->
                <?php 
                foreach ($companies as $company) {
                ?>
                    <a class="i" href="2.php?id=<?= $company['company_id'] ?>">
                        <div class="h">
                            <img src="images/<?= $company['company_image'] ?>">
                        </div>
                        <h2><?= $company['company_name'] ?></h2>
                    </a>
                <?php } ?>
            <?php } else { ?>
                <div class="n">empty</div>
            <?php }  ?>
</article>

<button id="button1" onclick="m(this.id)">click me to reload articles</button>
<button id="button2" onclick="m(this.id)">click me to reload articles</button>
<button id="button3" onclick="m(this.id)">click me to reload articles</button>

this code is in js file

<script>
function article(id) {
  url = new URL(window.location.href);
  url.searchParams.set("group_id", id);
  window.history.pushState("", "", url);

  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("article")...//write some code here to refresh or reload article element when you click button.
    }
  };
  url.search;
  xhttp.open("GET", "php/function.php"+url, true);
  xhttp.send();
}
</script>

I don’t know how can I reload, refresh or update the div content (part of page, not whole page) when buttom clicked using javascript ajax.

I need a function to get url content and reload the article div (not whole page, part of a page) something like ajax using java script but not jquery or other libraries.

How do I add a Multilevel dropdown to a Django template?

I am trying to add a dropdown to my navbar in base.html that shows multiple categories from a store. Each of these categories has a sub-category associated with it. I’ve created a model in Django that maps this relationship like so.

models.py

class CategoryView(models.Model):
    parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True)
    title = models.CharField(max_length=100) 
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

And I’m passing this model to the template using context processors as so

def categoriesdropdown(request):
    catg = CategoryView.objects.filter(parent=None)
    context = {'catg':catg}    
    return context

Now I am trying to display these categories and sub-categories as a multilevel dropdown using bootstrap. I have tried implementing mostly all solutions from the answers here:

Bootstrap 4: Multilevel Dropdown Inside Navigation

Bootstrap dropdown sub menu missing

https://mdbootstrap.com/docs/standard/extended/dropdown-multilevel/

But nothing seems to work.

Below is the dropdown from my template.

base.html

<div class="nav-item dropdown">
    <a href="#" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Categories</a>
    <ul class="dropdown-menu dropdown-menu2" aria-labelledby="dropdownMenuLink">
    {% for category in catg %}
        <li class="dropdown-submenu">
            <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ category.title }}</a>
            <ul class="dropdown-menu2" aria-labelledby="multilevelDropdownMenu1">
                {% for subcategory in category.children.all %}
                    <li><a href="#" class="dropdown-item">{{ subcategory.title }}</a></li>
                {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

I can see that all the categories and sub-categories are listed properly in the dropdown, however my sub-categories appear right below the categories and not as a next level dropdown.

enter image description here

Note: The dropdown toggle appears as is and doesn’t work.

base.css

.dropdown-submenu {
    position: relative;
  }
  
.dropdown-submenu .dropdown-menu2 {
top: 10%;
left: 100%;
margin-top: -1px;
}
  
.navbar-nav li:hover > ul.dropdown-menu2 {
    display: block;
} 

How do I get the category toggles to work and only display the sub-categories when the toggle is clicked or hovered over?