How to Prevent Arrow Rotation from Resetting When Switching Accordion Menus in JavaScript?

Beginner Learner

I’m working on an accordion menu that toggles the visibility of menu items and rotates an arrow icon to indicate the open/closed state. The JavaScript code works as expected in most cases, but I noticed an issue: when switching between accordion sections, the arrow rotation sometimes resets or behaves unexpectedly.

HTML Code

 <div class="accordion" onclick="accordian('section-1')">
                <div id="changemenu" class="accordian-text">Burger</div>
                <i class="down-arrow"></i>
            </div>
            <div class="menu-items" id="section-1">
                <div>
                    <input type="checkbox" name="sec-1" id="sc-1cb-1">
                    <label id="change1" for="sc-1cb-1">Cheese Burger</label>
                </div>
</div>
function accordian(disp) {
    var change = document.getElementById(disp); 
    var allsection = document.getElementsByClassName("menu-items");
    var allarrows = document.getElementsByClassName("down-arrow"); 

    for (let i = 0; i < allsection.length; i++) {
        allarrows[i].style.transform = "rotate(45deg)";
        allarrows[i].style.transition = "transform 100ms linear";
    }

    if (change.style.display === "block") {
        change.style.display = "none";
    } else {
        change.style.display = "block";
        var relatedAccordion = change.previousElementSibling;
        var arrow = relatedAccordion.querySelector(".down-arrow");
        arrow.style.transform = "rotate(225deg)";
        arrow.style.transition = "transform 100ms linear";
    }
}

this logic works but when i click quickly it auto updates or runs a bit slower….

JS deobfuscation with shift-ast

I am trying to convert some obfuscated js code using shift-ast.
I want to replace some CallExpressions with their string values.
So far I’ve been able to get the strings that I should use for the replacement in a stringArray by using the shift-refactor library.
I also have an array of all callExpressions names that I want to replace.
Here is a sample of the code:

function O(t, e) {
    var n = 392,
        r = 584,
        o = 407,
        i = 867,
        a = 392,
        c = 584,
        u = 867,
        s = 633,
        f = 985,
        l = 532,
        p = 392,
        h = 584,
        v = 631,
        d = 988,
        g = 1020,
        m = 677,
        y = I,
        b = Object[y(735)](t);
    if (Object[y(n) + y(r) + y(o) + y(i)]) {
        var w = Object[y(a) + y(c) + y(o) + y(u)](t);
        e && (w = w[y(s)]((function(e) {
            var n = y;
            return Object[n(p) + n(h) + n(v) + n(d)](t, e)[n(g) + n(m)];
        }))),
        b[y(f)][y(l)](b, w);
    }
    return b;
}

The stringArray I mentioned before is the variable I that is assigned to y and n in this sample code. I want to get the callExpressions y() and n().
I am struggling with how to ensure any replacements are in scope because the varaibleDeclarations use the same names. Finally I want to concatenate all strings that have the + sign.

I’ve tried to read up on shift-parser, shift-template and shift-scope but I can’t quite put it all together.
Please help me with this example so I can know how to handle it.

Muuri floating elements

In muuri.js, elements are affected by gravity by default and cannot be moved to any available space. How to allow elements to take up any free space and be unaffected by ‘gravity’?

Here’s an example of how it works in Gridstack.js; this is the
behaviour I want to achieve in muuri.js

Gridstack.js

Here’s how it works in muuri.js

muuri.js

Data Extraction for a Go Application from a JavaScript-Based Website

I’m working on an application to practice my skills, and the goal is to extract data from a website and make it available in an application written in Go. However, I’m running into some issues with the site.

The website I’m working with is https://projudi.tjgo.jus.br/BuscaProcesso. It seems to be entirely JavaScript-based, and when I inspect the traffic in the Network tab (XHR), I couldn’t find any requests returning JSON — only CSS and JavaScript files. I’ve considered working directly with the returned HTML, but there are some specific data and files that only appear after interacting with elements, like clicking on arrows or buttons.

I’d like to ask:

Is there any tool or technique you recommend to identify where this data might come from?
If there’s no clear endpoint for the data, what are the best practices for extracting information directly from the HTML, especially in cases where interaction with the site is required?
Thanks in advance for any tips or guidance!

Game grid/map display optimization ReactJs

I’m trying to display the map of a game using ReactJs.
The map is 100 tiles per 100 tiles so 10,000 in total like so:
map
Each tile can be colored with a custom color.

I built a store using mobx that holds the grid and the color of each tile and I’m basically looping through it to display the right color for each tiles.

Map.tsx:

const Map = observer(() => {
  const size = 100 * dashboardStore.zoom;
  const marginLeft = size * 0.75 + 2;
  const marginTop = size * 0.5 + 2;

  return (
    <div>
      <div className={styles.controls}>
        <Controls />
      </div>
      <div className={styles.map}>
        {dashboardStore.arrayY.map((_, yAxis) => (
          <div
            key={yAxis}
            className={styles.row}
            style={{
              width: `${(size + marginLeft + 2) * 100 + marginLeft}px`,
              height: `${size + 1}px`,
              marginLeft: yAxis % 2 ? `${marginLeft}px` : 0,
              marginTop: yAxis === 0 ? 0 : `-${marginTop}px`,
            }}
          >
            {dashboardStore.arrayX.map((_, xAxis) => {
              const index = yAxis * 100 + xAxis;
              return <Tile key={xAxis} index={index} color={dashboardStore.getTileColor(index)} />;
            })}
          </div>
        ))}
      </div>
    </div>
  );
});

Tile.tsx:

export type TileProps = {
  color?: string;
  index: number;
};

const Tile = observer(({ color, index }: TileProps) => {
  return (
    <div className={styles.container} onClick={() => dashboardStore.colorTile(index, dashboardStore.currentColor)}>
      <div className={styles.tileBorder} />
      <div className={styles.tile} style={{ backgroundColor: color }}>
        {dashboardStore.displayIndices ? index : ""}
      </div>
    </div>
  );
});

Everything works just fine, I’m rendering, the events trigger well, the colors display properly but I definitely have a performance issue. I can run the webpage on my MacBook Pro but it’s almost unusable on phone and and smaller devices (Basically on any devices since my laptop is quite high specs).

How can I optimize this so it can run on any device?

Thanks a lot.

How to setvalue of a textarea instant and call api after 2 second for efficiency

I’ve a textarea and I’d like to udpate text area text instantly as user enter text but I don’t like to hit api after every keystroke for obvious reason for efficiency.

I’ve tried to use debounce function but function is getting triggered as many times after every keystroke but with some delay that I’ve added in debounce

codesandbox link

export default function App() {
  const [text, setText] = useState("");

  function callAPI(value: string) {
    console.log(value);
    // CALL API HERE
  }

  const debouncedAPI = _.debounce(callAPI, 2000);

  function onChangeText(e) {
    const value = e.target.value;
    console.log(`value inside onChangeText: ${value}`);
    setText(value);
  }

  return (
    <div className="App">
      <textarea
        name="textarea"
        id=""
        value={text}
        onChange={(e) => {
          onChangeText(e); // Update the state
          debouncedAPI(e.target.value); // Call the debounced API with the latest value
        }}
      ></textarea>
    </div>
  );
}

The drilldown is not working after the first animation

I’ve created a drilldown chart to transact the graphs. The first configuration (from pie chart to bar chart) works. But from then on I couldn’t configure the gaugeOn function to make it work.

Code:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js"></script>
</head>

<div class="chart"></div>

<style>
  .chart {
    width: 400px;
    height: 430px;
  }
</style>

<script>
  document.addEventListener("DOMContentLoaded", () => {
    const chartUse = echarts.init(document.getElementsByClassName("chart")[0])

    function chartSystem() {
      return {
        source: {
          first: [
            ["x", "y", "childs"],
            ["Cars", 49, "cars"],
            ["Bikes", 65, "bikes"],
            ["Engines", 23, "eng"],
          ],
        },
        drill: {
          bar: [
            ["x", "y", "groups", "childs"],
            ["Mazda", 100, "cars", "bra"],
            ["Mass.", 120, "cars", "bra"],
            ["Accura", 150, "cars", "bra"],
            ["Kaw.", 20, "bikes", "arg"],
            ["Honda", 50, "bikes", "arg"],
            ["Yamaha", 80, "bikes", "arg"],
            ["V8", 60, "eng", "ned"],
            ["V10", 120, "eng", "ned"],
            ["V12", 20, "eng", "ned"],
          ],
          gauge: [
            ["name", "value", "groups"],
            ["Joao", 100, "bra"],
            ["Maria", 120, "bra"],
            ["Carlos", 20, "arg"],
            ["Bruna", 50, "arg"],
            ["Fabricio", 120, "ned"],
            ["Giovana", 20, "ned"],
          ],
        },
      }
    }

    let pullDataset = []
    let pullData = []
    let pullDrillBar = []
    let pullDrillGauge = []

    function chartSend() {
      const dfInit = chartSystem()
      const sourceIndex = dfInit.source
      const drillName = dfInit.drill

      pullDataset = [
        {
          source: sourceIndex.first, // Acessa "first"
          sourceHeader: true,
        },
      ]

      // Todos os dados de drill
      pullDrillBar = drillName.bar

      pullDrillGauge = drillName.gauge
    }

    chartSend()

    function chartFrameSwitch0() {
      const series0 = {
        type: "pie",
        color: ["#008cba", "#ff7400", "#00ff00"],
        radius: ["80%", "60%"],
        padAngle: 4,
        animationDurationUpdate: 1000,
        universalTransition: {
          enabled: true,
          divideShape: "split",
        },
        itemStyle: {
          borderRadius: 10,
          borderWidth: 1,
          borderColor: "#242832",
        },
        datasetIndex: 0,
        encode: {
          itemName: 0,
          value: 1,
          itemChildGroupId: 2,
        },
      }

      const option = {
        dataset: [pullDataset[0]],
        series: [series0],
      }

      // Define o gráfico inicial
      chartUse.setOption(option, { notMerge: true })
    }

    chartFrameSwitch0()

    // Evento de clique no gráfico de pizza
    function barOn() {
      chartUse.on("click", (params) => {
        if (params.seriesType === "pie") {
          const filtered = pullDrillBar.filter((row) => {
            return row[2] === params.data[2]
          })

          if (filtered.length) {
            const preparedData = [...filtered]
            drillCarrierBar(preparedData) // Gera o gráfico com o cabeçalho incluído
          }
        }
      })
    }

    barOn()

    // Evento de clique no gráfico de gauge
    function gaugeOn() {
      chartUse.on("click", (params) => {
        if (params.seriesType === "gauge") {
        
          const filtered = pullDrillGauge.filter((row) => {
            return row[2] === params.data[2]
          })

          if (filtered.length) {
            const prepared = filtered.slice(1).map((row) => ({
              name: row[0],
              value: row[1],
              groupId: row[2],
            }))
            drillCarrierGauge(prepared)
          }
        }
      })
    }

    gaugeOn()

    function drillCarrierGauge(data) {
      const series0 = {
        type: "gauge",
        data: [...data],
        universalTransition: {
          enabled: true,
          divideShape: "split",
        },
      }

      const option = {
        series: [series0],
      }

      chartUse.setOption(option, { notMerge: true })
    }

    function drillCarrierBar(data) {
      const xAxis0 = {
        type: "category",
        axisLabel: {
          color: "#000",
          fontSize: 14,
        },
      }
      const yAxis0 = {
        type: "value",
      }

      const series0 = {
        type: "bar",
        datasetIndex: 0,
        encode: {
          x: 0,
          y: 1,
          itemGroupId: 2,
          itemChildGroupId: 3,
        },
        color: ["#008cba", "#ff7400", "#00ff00"],
        animationDurationUpdate: 1000,
        universalTransition: {
          enabled: true,
          divideShape: "split",
        },
      }

      const option = {
        dataset: [
          {
            source: [...data],
            sourceHeader: false,
          },
        ],
        xAxis: [xAxis0],
        yAxis: [yAxis0],
        series: [series0],
      }

      // Atualiza o gráfico com as barras
      chartUse.setOption(option, { notMerge: true })
    }
  })
</script>

I just need to adjust the structure below to make it work when there is no dataset resource, as is the case with type: 'gauge'.

    function gaugeOn() {
      chartUse.on("click", (params) => {
        if (params.seriesType === "gauge") {
        
          const filtered = pullDrillGauge.filter((row) => {
            return row[2] === params.data[2]
          })

          if (filtered.length) {
            const prepared = filtered.slice(1).map((row) => ({
              name: row[0],
              value: row[1],
              groupId: row[2],
            }))
            drillCarrierGauge(prepared)
          }
        }
      })
    }

What is equivalent of `JSX.IntrinsicElements`?

I have crafted a library for next.js themes. Recently, I found this error here.

The latest version of Typescript 5.7.2 complains – TS2503: Cannot find namespace 'JSX'. What is the equivalent of JSX.IntrinsicElements that can be used to set the type of HTML Tags in React components?

How to calculate the value of CSS property ‘transform: rotateY (α)’ through JavaScript?

Let’s assume there is a style like the following:

.main{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    position: relative;
    height: 100vh;
    perspective: 1000px;
}
.page-L{
    position: relative;
    height: 100%;
    width: 30%;
    transform-origin: left;
    transform: rotateY(α);
}
.page-R{
    position: relative;
    margin: auto;
    height: 100%;
    width: 70%;
}

enter image description here

These two elements are children of “main”.

As you can see, you can clearly see that the element ‘page-L’ will undergo a deformation, and this will cause a visual change to its right side.

What should I do to obtain its changed value (height) through JavaScript and apply it to the element ‘page-R’?

Mobile pre-loader not centered in NextJS

I am facing issue understanding how mobile pre-loader works. So I have a pre-loader which is centered perfectly fine vertically and horizontally on Desktop screen. I can open up dev tools and see the same on all layouts it is perfectly centered and responsive.

Now the issue happens on my own phone. If I hit the url (My ip + port), the page loads and the pre-loader/text is not centered vertically but a bit to the bottom. If I touch the screen and interact with it then suddenly it comes into the centre. If I refresh the page then on first load it is centered. The issue only happens when I hit the url for the first time even a simple text won’t be centered no matter what style I apply.

It leads me to believe that I lack information on how mobile browser layout works and need some help understanding it.

I thought it might be an issue with my project but I created a fresh NextJS project.

This is my root page.js:

import Loading from “./components/Loading”;

export default function Home() {
  return (
    <Loading />
  );
}

And this is my Loading component:

import styles from "./Loading.module.css";

const Loading = () => {
  return (
    <div className={styles.landingLoadingDiv}>
      <p className={styles.loadingText}>NextJS</p>
    </div>
  );
};

export default Loading;

Loading.module.css:

.landingLoadingDiv {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100%;
  }
  
  .loadingText {
    font-size: 2rem;
    font-weight: 600;
    margin: 0;
  }

I know styling is not an issue, this is something that I don’t understand with how mobile rendering is working.

Here is what it visually looks like:
https://imgur.com/a/8hQhEHD

Inline edit save not working in multiple repeater

The code is just a simple widget. Here just i added two repeaters with a text control which i want to edit in inline. Now in the widget inline editing is working fine but it can’t saved.
But when i use one repeater only then it’s perfectly working the inline edit and save.
Now I used this add_inline_editing_attributes for inline editing. So to save the inline edit text for two repeaters what should i do?

protected function register_controls() {
    $this->start_controls_section(
        'content_section',
        [
            'label' => esc_html__( 'Test Plugin', 'test-plugin-td' ),
            'tab' => ElementorControls_Manager::TAB_CONTENT,
        ]
    );

    $repeater = new Repeater();
    $repeater->add_control(
        'text',
        [
            'label' => __( 'Business Hour', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::TEXT,
            'label_block' => true,
            'placeholder' => __( 'First Name', 'test-plugin-td' ),
            'default' => __( 'First Name', 'test-plugin-td' ),
            'dynamic' => [
                'active' => true,
            ],
        ]
    );
    $this->add_control(
        'business_hours',
        [
            'label' => __( 'Test Plugin', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::REPEATER,
            'fields' => $repeater->get_controls(),
            'default' => [
                [
                    'text' => __( 'First Name', 'test-plugin-td' ),
                ],
                [
                    'text' => __( 'Last Name', 'test-plugin-td' ),
                ],
            ],
            'title_field' => '{{{ text }}}',
        ]
    );

    $this->end_controls_section();


    $this->start_controls_section(
        'content_2section',
        [
            'label' => esc_html__( 'Test Plugin', 'test-plugin-td' ),
            'tab' => ElementorControls_Manager::TAB_CONTENT,
        ]
    );

    $repeskeater = new Repeater();
    $repeskeater->add_control(
        'text2',
        [
            'label' => __( 'Business Hour', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::TEXT,
            'label_block' => true,
            'placeholder' => __( 'First Name', 'test-plugin-td' ),
            'default' => __( 'First Name', 'test-plugin-td' ),
            'dynamic' => [
                'active' => true,
            ],
        ]
    );
    $this->add_control(
        'business_2hours',
        [
            'label' => __( 'Test Plugin', 'test-plugin-td' ),
            'type' => ElementorControls_Manager::REPEATER,
            'fields' => $repeskeater->get_controls(),
            'default' => [
                [
                    'text' => __( 'First Name', 'test-plugin-td' ),
                ],
                [
                    'text' => __( 'Last Name', 'test-plugin-td' ),
                ],
            ],
            'title_field' => '{{{ text2 }}}',
        ]
    );

    $this->end_controls_section();
}

protected function render() {
    $settings = $this->get_settings_for_display();
    echo '<ul class="test-plugin-td">';
    foreach ( $settings['business_hours'] as $index => $item ) :
        $text_key = $this->get_repeater_setting_key( 'text', 'business_hours', $index );
        $this->add_inline_editing_attributes( $text_key );
        ?>
        <li class="business-hour-item">
            <span <?php $this->print_render_attribute_string( $text_key ); ?>>
                <?php echo esc_html( $item['text'] ); ?>
            </span>
        </li>
        <?php
    endforeach;
    echo '</ul>';

    echo '<ul class="test-plugin-td">';
    foreach ( $settings['business_2hours'] as $index => $item ) :
        $text_key = $this->get_repeater_setting_key( 'text2', 'business_2hours', $index );
        $this->add_inline_editing_attributes( $text_key );
        ?>
        <li class="business-hour-item">
            <span <?php $this->print_render_attribute_string( $text_key ); ?>>
                <?php echo esc_html( $item['text2'] ); ?>
            </span>
        </li>
        <?php
    endforeach;
    echo '</ul>';
}

Datatable – Javascript – delete all rows is not working

I have a datatable inside a bootstrap modal. I am able to add/update/delete individual rows. But I am not able to clear all the rows. It does nothing.

HTML code:

<table class="table table-bordred" 
   id="tbl_outputdetail" name="tbl_outputdetail">
  <thead>
    <tr>
      <th>By Product</th>
      <th>Quantity Produced</th>
      <th></th>
      <th class="hide_column"></th>
    </tr>
    <tr>
      <th>
        <select style="width:300px;" class="form-control m-input"
           id="outputitem" name="outputitem">
        </select>
      </th>
      <th>
        <input type="text" class="form-control m-input" 
           id="outputqty" name="outputqty">
      </th>
      <th>
        <a href="#" id="output-add" name="output-add">
          <i class="la la-check"></i>
        </a>
        &nbsp;
        <a href="#" id="output-clear" name="output-clear">
          <i class="la la-close"></i>
        </a>
      </th>
      <th></th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

DataTable Definition:

tablew4 = $("#tbl_outputdetail").DataTable({
searching: false,
paging: false,            
serverSide:false,
ordering:false,
scrollX: true,
info:false,
columnDefs:[
{targets: [ 0 ], width: '400px'}, {targets: [ 1 ], width: '400px'},
{targets: [ 2 ], width: '100px'}, {targets: [ 3 ],   className: "hide_column"} 
],
"order": []
});

Code to delete the rows:

tablew4.clear().draw();
tablew4.rows().remove().draw();

Both methods do not clear the rows.

Treat Variables as single entities for deletion in a Text Box Using JavaScript

I have a text box field in my simple HTML/JavaScript-based form where users can insert variables, as shown in the example below:

The name of the product is ${productName}

When the user submits the form, a JavaScript function replaces the variable with its actual product value.

I’d like to implement a feature where, if the user places their cursor to the right of the variable ${productName} and presses the backspace key, the entire variable is deleted in one go, instead of deleting each character one at a time. Essentially, I want the variable to behave as a single, indivisible entity in the text box.

I’m unsure what the technical term for this feature is or how to start researching it. What’s the most efficient way to implement this behaviour?

Bun.js Packet losses in Websocket

I created a Websocket server using Bun.serve(). In this server, when a new client connects, I send it 1 million packets with a for loop. But these packets are interrupted. Hundreds of thousands of packets are not sent to the client. I used the ws package from NPM instead of Bun’s Websocket and the problem is solved. How can Bun, which claims to be a much faster Websocket server than ws, experience packet loss? Is there a solution to this or should I use ws until this problem is noticed?

server.js

const Bun = require("bun");

Bun.serve({
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("Only WebSocket connections are supported.", {status: 400});
  },

  websocket: {
    open(socket) {
      const start = performance.now();

      for (let i = 0; i < 1_000_000; i++) socket.send(JSON.stringify({"type": "MESSAGE_CREATE", "data": {"content": i}}));

      const end = performance.now();
      const duration = end - start;

      console.log(duration.toFixed(2) + " ms");
    },

    close(socket) {
      console.log("Client disconnected");
    },

    error(socket, error) {
      console.error("WebSocket error:", error);
    }
  },

  port: 8080,
  reusePort: true
});

client.js

const WebSocket = require("ws");
const ws = new WebSocket("ws://localhost:8080");

var count = 0;
var start_date;

ws.on("message", message => {
  count++;
  if (count === 1) console.log(message.toString() + " 0 ms"), start_date = Date.now();
  if (count >= 999_990) console.log(message.toString() + " " + (Date.now() - start_date) + " ms");
});

setInterval(() => console.log(count), 5000);

Solution without packet loss but with ws library.

server.js

const http = require("http");
const WebSocket = require("ws");
const Server = http.createServer();
const ws = new WebSocket.Server({server: Server});

ws.on("connection", socket => {
    const start = performance.now();

    for (let i = 0; i < 1_000_000; i++) socket.send(JSON.stringify({"type": "MESSAGE_CREATE", "data": {"content": i}}));

    const end = performance.now();
    const duration = end - start;

    console.log(duration.toFixed(2) + " ms");
})

Server.listen(8080);

Changing display property dynamically with Javascript and If

I want to change the display property of a div tag based on its current display property.

When display = “None”, it should switch to “flex” by clicking on it and viseversa.

I wrote the following js code:

window.onload = function showHideSideMenuMyFolders() {

    var test = document.getElementById("sideMenuLowerPartFolders_MyFolders");
    
    if (test.style.display === "Flex") {
        test.style.display = "None";
    }
    else {
        test.style.display = "Flex";
    }
}

It should activate by clicking on a span element in the DOM.

<span id="showSideMenuMyFolders" onclick="showHideSideMenuMyFolders()">

However, it is not working.

Can somebody see my mistake?