Show a warning if the user tries to enter more characters than allowed in the input

At the moment, my website has an input field into which the user can enter any characters.
According to the requirement, the field length cannot be more than 5 characters, otherwise a warning appears and nothing is allowed to be entered. It’s done!

Currently, a warning appears when entering the fifth character. But tell me: how can I make it so that the warning appears only when the user tries to enter the sixth character?

Current behavior:

The user enters the character “a” – OK

The user enters the character “b” – OK

The user enters the character “c” – OK

The user enters the character “d” – OK

The user enters the character “e” – a warning appears and user cannot enter the next symbol

Expected behavior:

The user enters the character “a” – OK

The user enters the character “b” – OK

The user enters the character “c” – OK

The user enters the character “d” – OK

The user enters the character “e” – OK

The user tries to enter the symbol “f” – the user sees a warning and cannot enter the symbol “f”

function isLength(title_) {
  return title_.length < 5;
}

const Title = () => {
  const [title, setTitle] = useState('');

  useEffect(() => {
    if (isLength(title)) {
      onChange(title);
    }
  }, [onChange, title]);

  const onChangeTitle = (event: { target: { value: string } }) => {
    if (event.target.value.length < 6) {
      setTitle(event.target.value.trimStart().replace(/s+/g, ' '));
    }
  };

  let errorMessage = <div />;

  if (!isLength(title)) errorMessage = <div>String at most 5 characters</div>;

  return (
    <div>
      <input id="title" onChange={onChangeTitle} value={title} />
      {errorMessage}
    </div>
  );
};

How to display names in a loop in json api in vue application?

I have an element which has childElements in 3 levels, so my element is object like this:

element: {
   childElements: {
      data: Array()
   }
   name:
   id:
}

So my structure is like this:

-> Element A
   -> Element B
      -> Element C
         ->Element D
            ->Element E

As you see, there are 5 elements, but in my element object, I cannot get these 5 levels. So for each object, I should make an API call, and get the details of it. Details with API call has the same structure. So I should get childElements with it and childElements.data includes name and ID, too. So it should be in a loop or recursive and since childElements.data is an array I should have a for loop to show the names of each element. I want something simple and in my vue application, write the element’s name in the view. How can I achieve this?

How can I remove the white blog post background without affecting the posts display in the homepage?

https://www.mralshabib.com/

How can I remove the white background in the post page?
(https://i.stack.imgur.com/hujrK.png)

Without affecting the white background of the posts in the homepage..
(https://i.stack.imgur.com/g50Xc.png)

I tried modifying this, but when changing anything the both sides/widgets got affected.
<article class="post hentry"></article>

So, how to customize the post page only?

Use promise to modify reactive data. The position of promise will cause the number of triggers to decrease

    const list = reactive([1, 2, 3, 4, 5]); 
    const handleClick = () =>{
        list.push(...[11, 12, 13, 14, 15]);
        list.push(...[16, 17, 18, 19, 20]);
        Promise.resolve().then(() => {
            list.push(33)
        });
        
    };
    const list = reactive([1, 2, 3, 4, 5]);
    const handleClick = ()=>{
        Promise.resolve().then(() => {
            list.push(33)
        });
        list.push(...[11, 12, 13, 14, 15]);
        list.push(...[16, 17, 18, 19, 20]);
    };

first function will trigger twice vue hooks onUpdated,but second will trigger once,can anyone tell me why,thanks

The arrayBuffer generated by the 3D model stl file occupies too much space, causing Safari to crash on the mobile end. How to solve this problem?

The arrayBuffer generated by the 3D model stl file occupies too much space, causing Safari to crash on the mobile end. How to solve this problem?
I use vtk.js to handle the display issue of stl files, use fetch to request stl files, return the result as arrayBuffer, and then use vtk.js’s arrayBuffer parser to parse arrayBuffer data.
How should I handle it?

I try to request stl files one by one, also try to asynchronously request all files, and try to place fetch in webwork. After the request is completed, I send arrayBuffer data to the main thread, but the arrayBuffer is too large, A single stl file’s arrayBuffer will have millions.
Use fetch streaming data? I’m not sure if vtk.js supports it?

How to access localstorage from a popup window spawned by an iframe

On a webpage belonging to the origin X, I have an iFrame belonging to the origin Y. In the iFrame is a button that opens a popup window which navigates to a webpage belonging to domain Y. When the iFrame page loads, it sets a localstorage key “abc”. However, I do not have access to the localstorage of the iFrame from the popup. Is there any particular security policy reason for this to happen?

Example code:

iFrame.htm:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        const setKey = ()=>{
            localStorage.setItem("abc","Good day")
        }
        const openPopup = ()=>{
            window.open("popup.htm","_blank","popup,left=100,top=100,width=320,height=600")
        }
    </script>
</head>
<body onload="setKey()">
    <h1> iFrame </h1>
    <button onclick="openPopup()"> Open popup </button>
</body>
</html>

Popup.htm:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        const accessStorage = ()=>{
            const abc = localStorage.getItem("abc")
            console.log(abc) //Null
        }
    </script>
</head>
<body onload="accessStorage()">
    <h1> Popup</h1>
</body>
</html>

Surprisingly, this works perfectly if I open iframe.htm in a new browser window instead of embedding it in my webpage belonging to domain X.

Reset an row selections on page load within material react table

Using Material React Table V1 is there a prop perhaps within initialState to ensure that on page load of any table, ensure that no rows are selected.

I have something like this:

import { MaterialReactTable } from 'material-react-table';

      <MaterialReactTable
        key={refreshPage}
        columns={myTableColumns}
        data={myTableContent}
        enableColumnResizing
        enableFullScreenToggle={false}
        enableHiding={false}
        enablePinning={!isMobile}
        enableExpanding
        enableStickyHeader
        enableRowSelection
      />

I basically want to be able to reset any row selections whenever the table is loaded on page load.

I tried to look out for something like:

table.toggleAllRowsSelected(false) on page load but I don’t have access to table

livewire wire:ignore but need updated value

I am using a tagify component with wire:ignore and i want to update the value dynamically after input change. I am failing to update value.

Then I manually trigger a Livewire action using JavaScript when the input value changes.With this setup, changes to the customInput field will trigger the handleCustomInputChange Livewire method, allowing you to update the livewireManagedValue property.

But nothings works.

here is my blade:

<div class="row g-3 mb-3" style="margin-top: 50px" wire:ignore>
                        <input type="hidden" wire:model="livewireManagedValue">

                        <input id="customInput" name='input-custom-dropdown' class='some_class_name'
                            placeholder='write some tags' value=''>

                    </div>


@push('body_resources')
        <script src="{{ asset('assets/tagify/tagify.min.js') }}"></script>

        <script>
            var input = document.querySelector('input[name="input-custom-dropdown"]'),
                // init Tagify script on the above inputs
                tagify = new Tagify(input, {
                    whitelist: ["A# .NET", "PHP", "A-0 System", "A+", "A++", "ABAP", "ABC"],
                 
                    maxTags: 10,
                    dropdown: {
                        maxItems: 20, 
                        classname: "tags-look", 
                        enabled: 0, 
                        closeOnSelect: false 
                    }
                })
        </script>
        <script>
            document.addEventListener('livewire:load', function() {

                var customInput = document.getElementById('customInput');
                customInput.addEventListener('input', function() {
                    // Get the value from the custom input
                    var value = customInput.value;

                    // Trigger the Livewire action with the updated value
                    Livewire.emit('handleCustomInputChange', value);
                });
            });
        </script>
    @endpush

In controller:

public $livewireManagedValue;

// Livewire method to handle changes from JavaScript
public function handleCustomInputChange($value)
{
    // Update Livewire-managed value
    $this->livewireManagedValue = $value;
}

What would be the workaround for this? Any help is greatly appreciated.

without getting the elementid from a webpage, how to capture digits of the second word in a webpage using javascript

without getting the element id of the webpage, how to capture the digits of the word having the same word in a webpage?

For Example: (Word1) Data: 150 (Word2) Data: 250

I am trying to capture the digits right next to (Word2) which is 250 and im sending that data to a csv file. Below is a part of my code which I have tried with several regular expressions in javascript but I ended up getting the Data: 150. Any inputs is highly appreciated. Thank you very much.

const textContent = document.body.textContent || document.body.innerText;
const DataMatch = /Data:D*(d+)/i.exec(textContent);

How to use JavaScript to modify the content of a Discord input box?

I am developing a Chrome browser extension based on Discord.

I used this piece of code, but still couldn’t modify the content of the input box.


const inputBoxElem = document.querySelectorAll('[contenteditable="true"]')[1]

function replaceValue(selector, value) {
  const el = selector;
  if (el) {
    el.focus();
    document.execCommand('selectAll');
    if (!document.execCommand('insertText', false, value)) {
      el.value = 'new text';
    }
    el.dispatchEvent(new Event('change', {bubbles: true}));
  }
  return el;
}

replaceValue(inputBoxElem, "Hello")

I want to modify the input box content by selecting all text and pasting new content, but still cannot make the modification.


(async () => {
    let node = document.activeElement;

    if (!node) {
        return;
    }

    while (node.shadowRoot) {
        node = node.shadowRoot.activeElement;
    }

    const initText = getNodeText(node);

    if (!isEditAbleNode(node)) {
        return;
    }


    let text = "hello, change input box content";

    try {

        if (isInputNode(node)) {
            node.value = text;
            node.dispatchEvent(
                new Event("input", { bubbles: true, cancelable: true })
            );
            return;
        }

        selectContent(node);
        await sleep(200);

        pasteContentEvent(node, text);
        await sleep(200);

        if (getNodeText(node).startsWith(initText)) {
            pasteContentCommand(node, text);
            await sleep(100);
        } else {
            collapseToEnd(node);
        }
    } catch (err) {
        console.log("error: ", err.message);
    } finally {
    }
})();


function isInputNode(node) {
    return node.nodeName === "INPUT" || node.nodeName === "TEXTAREA";
}

function isEditAbleNode(node) {
    return node.hasAttribute("contenteditable");
}

function selectContent(node) {
    node.focus();
    const range = document.createRange();
    range.selectNodeContents(node);

    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
}

function pasteContentEvent(node, text) {
    node.focus();
    const data = new DataTransfer();
    data.setData("text/plain", text);

    const event = new ClipboardEvent("paste", { clipboardData: data });
    document.dispatchEvent(event);
    data.clearData();
}

function pasteContentCommand(node, text) {
    node.focus();
    document.execCommand("insertText", false, text);
}

function collapseToEnd(node) {
    node.focus();
    const selection = window.getSelection();
    selection.collapseToEnd();
}

function getNodeText(node) {
    if (isInputNode(node)) {
        return node.value;
    }
    return node.innerText || node.textContent || "";
}

function sleep(delay) {
    new Promise((resolve) => {
        const timer = setTimeout(() => {
            clearTimeout(timer);
            resolve();
        }, delay);
    });
};

SlickJS speed command does not update

I have a roulette game im trying to make for my website for fun. Some reason the SlickJS speed doesnt update after the first round. This func gets called every 100ms. It works for one round, but then freezes. The Roulette.Speed does update perfectly, it goes from 50 => 1500 and resets each round.

`if (Date.now() < LastAction + 100) {
return;
}

      LastAction = Date.now();

      console.log("Speed:"+Roulette.Speed);
      $('.my_slider').slick('slickSetOption', 'speed', Roulette.Speed, true);

      switch (Roulette.State)
      {
        case "BetPhase":
            document.getElementById("roulettetext").innerHTML = "Starting in " + Roulette.Timer.toFixed(1);
            break;
        case "RollPhase":
              // ive also tried $('.my_slider').slick('slickPlay') and 'slickPause'. Same thing happens
              document.getElementById("roulettetext").innerHTML = "Rolling!";
            break;
        case "PayoutPhase":
            document.getElementById("roulettetext").innerHTML = "Rolled a " +Roulette.Number+"!";
            break;
        case "SetupNewGame":
            break;
      }`

Here is my Slick

$('.my_slider').slick({
            accessibility: false,
            pauseOnFocus: false,
            pauseOnHover: false,
            touchMove: false,
            swipe: false,
            draggable: false,
            slidesToShow: 5,
            slidesToScroll: 1,
            speed: 250,
            autoplay: true,
            autoplaySpeed: 1,
            infinite: true,
            adaptiveHeight: true,
            cssEase: 'linear'
            }).on('wheel', (function(e)
            {
                e.preventDefault();
                if (e.originalEvent.deltaY < 0)
                    $(this).slick('slickNext');
            }));```

Change div background color automatically when color-scheme changes

I’m using 3 radio buttons to switch color-schemes (automatic depending on system, light, and dark) and setting several css variables that will change my website’s colors automatically on color-scheme changes. It works on the css-controlled div, but the problem is, when I get these variables into my js, the changes don’t occur automatically upon radio button presses. I may need some kind of listener, but I don’t know how to do that.

Here’s what I’ve attempted.

<html>
  <head>
    <style>
      html {
        --background-light : #F5F5F6;
        --background-dark  : #1D1D1F;
      }

      :root {
        color-scheme: light;
        --background : var(--background-light);
      }

      @media (prefers-color-scheme: dark) {
        :root {
          color-scheme: dark;
          --background : var(--background-dark);
        }
      }

      [color-scheme="light"] {
        color-scheme : light;
        --background : var(--background-light);
      }

      [color-scheme="dark"] {
        color-scheme : dark;
        --background : var(--background-dark);
      }

      .mydivs {
        width : 100vw;
        height : 100vh;
      }

      #change-with-css {
        background : var(--background);
      }
    </style>
  </head>

  <body>
    <form id="color-scheme">
      <div>
        <input checked type="radio" id="auto" class="toggler" name="theme" value="auto"/>
      </div>
      <div class="color-boxes">
        <input type="radio" id="light" class="toggler" name="theme" value="light"/>
      </div>
      <div class="color-boxes">
        <input type="radio" id="dark" class="toggler" name="theme" value="dark"/>
      </div>
    </form>

    <div id="change-with-css" class="mydivs"></div>
    <div id="change-with-js" class="mydivs"></div>
    <script>
      const switcher = document.querySelector("#color-scheme");
      const doc = document.firstElementChild;
      const setTheme = (theme) => doc.setAttribute("color-scheme", theme);
      switcher.addEventListener("input", (e) => setTheme(e.target.value));

      const myJsDiv = document.querySelector("#change-with-js");
      const myDivBg = getComputedStyle(document.body);
      myJsDiv.style.background = myDivBg.getPropertyValue("--background");
    </script>
  </body>
</html>

Kindly help me in vanilla js format if possible, thank you.

400 Bad Request error using PayPal v2 createOrder

Here is the frontend code:

const createOrder = () => {
// Order is created on the server and the order id is returned

return fetch(`${serverUrl}/api/orders`, {
  method: "POST",
   headers: {
    "Content-Type": "application/json"
  },

  // use the "body" param to optionally pass additional order information

  // like product skus and quantities

  body: JSON.stringify({
    cart: [
      {
        id:'woodcandysofa',
        name:'Wood Candy Sofa',
        quantity: 1,
        price: 399
      },
    ],
  }),
})

.then((response) => response.json())
.then((order) => order.id);

};

Here is the backend:

module.exports.createOrder = async (cart) => {
    // use the cart information passed from the front-end to calculate the purchase unit details
    console.log(
      "shopping cart information passed from the frontend createOrder() callback:",
      cart,
    );
      const totalPrice = cart.reduce ((prev, curr) => prev + curr.price, 0);
    const accessToken = await generateAccessToken();
    const url = `${base}/v2/checkout/orders`;
    const payload = {
      intent: "CAPTURE",
      purchase_units: [
        {
          amount: {
            currency_code: "EUR",
            breakdown: {
              item_total: totalPrice
            },
            value: totalPrice
          },
          items: cart.map (item => ({
            name: item.name,
            quantity: item.quantity,
            unit_amount: { currency_code: 'EUR', value: item.price * item.quantity}
          }))
        },
      ],
    }

And this is the error I get on the backend:
_Response [Response] { [Symbol(realm)]: null, [Symbol(state)]: { aborted: false, rangeRequested: false, timingAllowPassed: true, requestIncludesCredentials: true, type: 'default', status: 400, timingInfo: { startTime: 11720.420841999352, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: 11720.420841999352, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null }, cacheState: '', statusText: 'Bad Request',

If I don’t pass any items and just amount (currency_code and value) then it works fine. But I need that information about WHAT was purchased exactly.

Any ideas? Thanks for reading.

Tried to integrate PayPal v2 and provided the items array. Without the items array, it works – with it, it fails.

Three.js + Theatre.js Moving all keyframes

I’m using the fantastic Theatre.js[1] library to animate part of my website.

Now want to go back and add some animation at the beginning.

In the Sequence Editor, I can’t seem to select all points / keyframes and move them using the studio UI.

Am I going to have to manually move every part of the animation over?

The position of the keyframes relative to each other is more of an art than a science, and it’ll probably mess up the work I’ve done so far.

Is there a bit of javascript that I could paste into the console that would simply loop through all the points and shunt them to the right, by a fixed amount of time?

[1] https://www.theatrejs.com/docs/latest/manual/Studio#sequence-editor