Move embedded code output to

Is it possible to move output value of embedded code to a <img src”>?

The embed code example:

<!-- Paste this where you want the article to appear --> 
    <div 
    data-article="programma"
    data-param-teamcode="245124"
    data-param-gebruiklokaleteamgegevens="NEE"
    data-param-aantalregels="1"
    data-param-aantaldagen="60"
    data-param-eigenwedstrijden="JA"
    data-param-thuis="JA"
    data-param-uit="JA"
    data-format-wedstrijddatum="DD-MM-YYYY"
    data-fields="thuisteam, thuisteamlogo" 
    ></div>

has the following output:

<div data-article="programma" data-param-teamcode="245124" data-param-gebruiklokaleteamgegevens="NEE" data-param-aantalregels="1" data-param-aantaldagen="60" data-param-eigenwedstrijden="JA" data-param-thuis="JA" data-param-uit="JA" data-format-wedstrijddatum="DD-MM-YYYY" data-fields="thuisteam, thuisteamlogo"><table class="article programma"><thead><tr><th><span class="string">Thuisteam</span></th><th><span class="string">Thuisteam logo</span></th></tr></thead><tbody><tr><td><span class="string">De Weide 2</span></td><td><span class="string">https://binaries.sportlink.com/KNVB-production-DOCUMENT/280B8A5A8EF81EC7C0CAC19267EC8683?expires=1724879248&amp;sig=a6a97cac503271e0515ce3dfd4d66b330d819e25</span></td></tr></tbody>        </table></div>

The URL in the output is a link to an image and I would like to view the image in the browser instead of just a link.

Is it possible to move this with javascript/jquery to <img src=''>??

Didn’t try anything yet

Any potential pitfalls in implementation of debounce if we invoke the function normally instead of ‘apply’?

We often find the debounce implementation with func.apply(this, args) I guess this is just to make sure the ‘this’ points to the context of the inner function that’s returned.

const debounce = function (func, wait = 1000) {
    let timer = null;

    return function (...args) {
      clearTimeout(timer);

      timer = setTimeout(() => {
        func.apply(this, args)
      }, wait);
    };
  };
  
  const handleSearch = function(param1, param2){
     console.log(param1 + param2);
  }
  
  let debouncedFunc = debounce(handleSearch, 1000);
  debouncedFunc("hello ", "world");

But what if we simply invoke the function with args without worrying about apply or this I get the same results. So is there any potential pitfalls with this approach due to which we generally implement like the former?

     const debounce = function (func, wait = 1000) {
        let timer = null;

        return function (...args) {
          clearTimeout(timer);

          timer = setTimeout(() => {
            func(...args)
          }, wait);
        };
      };
      
      const handleSearch = function(param1, param2){
         console.log(param1 + param2);
      }
      
      let res = debounce(handleSearch, 1000);
      res("hello ", "world");

How to check if video codec is supported

I would like to determine if a video can be played in the browser or not before the user tries to play the video.

For example, I have this video that when I inspect it the codecs returned are: MPEG-4 AAC, H.264. As far as I understand the codec is H.264.
On Developer.mozilla.org I found a nice list of popular codecs

Now, when I want to check this with javascript and I found code like this

MediaRecorder.isTypeSupported('video/mp4; codecs="avc1.42E01E')

Is it possible instead of using a specific h.264 level like avc1.42E01E (which I don’t have) to lookup support for H.264 instead, something like

MediaRecorder.isTypeSupported('video/mp4; codecs="h.264')

React Form Submits Cause Page Reload Despite Using e.preventDefault()

I’m working on a React component with a form that sends a message using a custom hook. Despite using e.preventDefault() in the form’s onSubmit handler, the page reloads every time I submit the form, which interrupts my debugging process and resets the state. I’ve verified that e.preventDefault() is being called correctly, and there are no additional forms or submit buttons on the page that could be causing this behavior. I’m not seeing any JavaScript errors in the console that could explain this issue. I’ve also checked that the form is set up correctly, with the button type as submit.
here’s the component

`
import { FaSearch } from "react-icons/fa";
import useSendMessage from "../../hooks/useSendMessage";
import { useState } from "react";

const SearchInput = () => {
  const { loading, sendMessage } = useSendMessage();
  const [message, setMessage] = useState("");

  const handleMessageSend = async (e) => {
    e.preventDefault(); // Prevents default page reload

    if (!message) return;
    await sendMessage(message);
    setMessage("");
  };

  return (
    <form onSubmit={handleMessageSend}>`
      <input`
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        placeholder="Type a message"
      />
      <button type="submit">
        {loading ? <span>Loading...</span> : <FaSearch />}
      </button>
    </form>
  );
};

export default SearchInput;`

any insights would be helpful

What I Tried:

I set up a React form with an onSubmit handler that calls e.preventDefault() to stop the page from reloading. I implemented a custom hook to handle sending messages via an API. I also verified that the form was correctly configured, with the submit button type set to “submit”.

What I Expected:

I expected the form to submit the message asynchronously without reloading the page. The state should update with the new message, and the input field should reset to an empty string.

What Actually Happened:

Despite calling e.preventDefault(), the page still reloads every time I submit the form, which resets the component state and interrupts the form submission process. I can’t debug the issue properly because the page reload prevents me from seeing console logs or tracking state changes.

here’s my useSendMessage

import toast from "react-hot-toast";
import useConversations from "../zustand/useConversations";
import { useState } from "react";

const useSendMessage = () => {
  const [loading, setLoading] = useState(false);
  const { messages, setMessages, selectedConversation } = useConversations();

  const sendMessage = async (message) => {
    try {
      setLoading(true);
      const res = await fetch(
        `/api/messages/send/${selectedConversation._id}`,
        {
          method: "POST",
          headers: {
            "Content-type": "application/json",
          },
          body: JSON.stringify({ message }),
        }
      );

      const data = await res.json();
      if (data.error) throw new Error(data.error);

      setMessages([...messages, data]);
    } catch (error) {
      toast.error(error.message);
    } finally {
      setLoading(false);
    }
  };

  return { loading, sendMessage };
};

export default useSendMessage;

here’s zustand

import { create } from "zustand";

const useConversations = create((set) => ({
  selectedConversation: null,
  setSelectedConversation: (selectedConversation) =>
    set({ selectedConversation }),
  messages: [],
  setMessages: (messages) => set({ messages }),
}));

export default useConversations;

How to share information between browser tabs that are opened from specific tab

If I open an app (SPA) in multiple tabs (manually opened tabs), I want to make some of the information persistent as a session for each tab. session storage does this job.

But when I right click on an anchor and then select “open in new tab” in specific tab, I want to pass that session storage into the new opened tab.

The local storage does not work for this, because I want each tab to hold independent data, but those tabs that are opened from another tab to access the opener data.

There should be a place to keep a data in each tab, where:

  • tabs that are opened from another tab, to have access to that opener place
  • tabs that are manually opened to not be able to read data from that place

When I middle-click with the mouse on the refresh button of the browser, It opens a new tab and passes the session storage from the current tab into the new opened tab. I want something like this to happen when I right click and select “open in new tab” on an anchor.

How I can achieve this behaviour?

Without adding information to the link url/query params

Magically changing values in JS object

I dont know how to describe this better but I have never seen a behaviour like this. 😀

I have a JS object emospro with an attribute emospro.billing which is an array with four values.

I filled the object with some data and then checked it like this:

console.log(emospro.billing);
console.log(emospro);
console.log(emospro.billing);

The reason for this construction is that the results a strange.

The first log gave me this:

['1000000635', 'not_set', 'be/STADT/0000', 247.81]

which is what I expected. The third log gave me the same:
['1000000635', 'not_set', 'be/STADT/0000', 247.81]

So far so good. But then the second log with the whole emospro-Object returned this:

{
    "billing": [
        "u3f_3g8hEOuyhiyF*VAnxS4bQoLVQHXW9feqghZKHWo",
        null,
        null,
        247.81
    ]
}

It encrypted/hashed somehow the first value, nulled the second and third and only the last value is correct. I altered the last value by myself to check if it is reacting and it does. On the first three values I have no influence in the second log.

How is this even possible without influencing the log before or after??

I am confused. Somebody with an idea?

Schema registry taking old schema id while decoding

We have written kafka consumer using in nodejs using Kafkajs library. And using @kafkajs/confluent-schema-registry to deserialize the message.

After initializing schema registry, If I call registry.decode method to decode I facing "ConfluentSchemaRegistryValidationError: invalid payloadn at JsonSchema.validatePayload error.

Also If I console registry after initialisation, Its taking older schema ID.

SchemaRegistry {
  cacheMissRequests: {},
  api: {
    _manifest: Manifest {
      host: 'abc', //dummy data**your text**
      allowResourceHostOverride: false,
      parameterEncoder: [Function: encodeURIComponent],
      bodyAttr: undefined,
      headersAttr: undefined,
      authAttr: undefined,
      timeoutAttr: undefined,
      hostAttr: undefined,
      clientId: 'Confluent_Schema_Registry',
      gatewayConfigs: [Object],
      resources: [Object],
      context: {},
      middleware: [Array]
    },
    Schema: { find: [Function: resourceMethod] },
    Subject: {
      all: [Function: resourceMethod],
      latestVersion: [Function: resourceMethod],
      version: [Function: resourceMethod],
      registered: [Function: resourceMethod],
      config: [Function: resourceMethod],
      updateConfig: [Function: resourceMethod],
      register: [Function: resourceMethod],
      compatible: [Function: resourceMethod]
    }
  },
  cache: Cache {
    getLatestRegistryId: [Function (anonymous)],
    setLatestRegistryId: [Function (anonymous)],
    getSchema: [Function (anonymous)],
    setSchema: [Function (anonymous)],
    clear: [Function (anonymous)],
    registryIdBySubject: {},
    **schemasByRegistryId: { '100248': [Object] }**
  },
  options: { JSON: { ajvInstance: [Ajv] } }
}

How can make registry to take latest schema and decode message using latest schema.

Also is there a way to decode message using local schema?

Also is there a way to decode message using local schema?

Adding an environmental variable at the start of a package.json script prevents cd ./android from working – APP_ENV=production cd ./android

So I just noticed that if I have the following script in my package.json file:

"android:build:release": "APP_ENV=production cd ./android && ./gradlew clean bundleProductionRelease",

and I run it like this:

yarn android:build:release

It said "command not found: ./gradlew" because the cd to the android folder is not working, but as soon as I removed APP_ENV=production, it worked.

Any idea why is this happening?

how can I improve myself algorithmically in beginner level javascript [closed]

I am learning javascript and golang, but I could not advance myself in algorithm. There is no problem in understanding the code, I can interpret the code I see, but I have difficulty writing on my own, I don’t know where to start, how to start, where to start, where to do what to do.

örnek vermek gerekirse:





your text`We have learned four basic array methods, pop(), push(), shift() and unshift(), they are used to add or remove an array of elements. But their disadvantage is that they can only add or remove elements in order. This time we learn a new method: splice(). It can add and/or remove elements at any location in the array. Its usage:

arrayObject.splice(startindex, deleteCount [,element1, element1, ...,elementx])
parameter1 and parameter2 are used to remove element. parameters in the [] is some elements to add, if we omitted it, splice() only performs removal operations.

We can write that way:

arrayObject.splice(a,b,[c,d,e,...,z])
Then ask yourself three questions:

Where do I start removing elements?   ---- a
How many elements need to be removed? ---- b
What elements should be added after the removal of the element?
--- c,d,e,...z
Some examples to help you understand splice()

function removeOdd(arr){
  //remove odd number of arr
  for (var i=arr.length;i>=0;i--)
    if (arr[i]%2) arr.splice(i,1)
  return arr;
}
console.log(removeOdd([1,2,3,4,5]))   //output: [ 2, 4 ]
console.log(removeOdd([1,3,5,7,9]))   //output: []
The example above removes all the odd numbers from the array, leaving all the even numbers.

Why don't I start to traverse the array from index0? because we
need to pay special attention to that some of the methods of the array directly modify the original array. In some cases, if you forget the fact, you will get the wrong result. In the example above, if we start to traverse the array from index0, some element will be missed:

function removeOdd(arr){
  //remove odd number of arr
  for (var i=0;i<arr.length;i++)
    if (arr[i]%2) arr.splice(i,1)
  return arr;
}
console.log(removeOdd([1,3,5,7,9]))   //output: [3,7]
because:
When i=0, arr[i]=1, arr.splice(0,1) then arr=[3,5,7,9], i++
then i=1, arr[i]=5, element 3 is missed because its index is became to 0
so, we got an wrong answer...
Look at the following example:

function removeOdd(arr){
  //remove odd number from arr
  for (var i=arr.length;i>=0;i--)
    if (arr[i]%2) arr.splice(i,1)
  return arr;
}
function removeEven(arr){
  //remove even number from arr
  for (var i=arr.length;i>=0;i--)
    if (arr[i]%2==0) arr.splice(i,1)
  return arr;
}
var arr=[1,2,3,4,5]
removeOdd(arr)
console.log(arr)   //output: [ 2, 4 ]
removeEven(arr)
console.log(arr)   //output: []
Perhaps the purpose of running removeEven is to remove the even number, leaving the odd number. But in fact, we get an empty array, which is not what we want. How to improve it?

In this case, you can use slice() to make a "copy" for the array. In the previous study of string objects, We have known the slice, which is used to intercept a string. For an array object, the usage of slice() is similar to the stringObject method. Some people may want to use "=" operator to implement backup, but that is wrong. See the example:

var originalArray=[1,2,3,4,5];
//use "=" operators
var new1=originalArray;   
//use slice() without parameters can make a "copy"
var new2=originalArray.slice();  
//then three array all are [1,2,3,4,5], let's us do something..
new1.push(100);
new2.push(111);
//Let's look at the changes in these arrays:
console.log(new1)
console.log(new2)
console.log(originalArray)

//output:
[ 1, 2, 3, 4, 5, 100 ]
[ 1, 2, 3, 4, 5, 111 ]
[ 1, 2, 3, 4, 5, 100 ]
We can see that the value of the original array will be changed with the new1. Because new1 use "=" operator, just do a shortcut to the original array; The value of the original array does not change with new2. Because it uses slice() to create a new array, which has no relation to the original array.

So, we can use the slice() without the parameter to create a copy of the original array. However, if the original array is a 2D array or multidimensional arrays, the use of slice() is not enough. see example:

var originalArray=[[1,2,3],[4,5]];
//use slice() without parameters can make a "copy"
var newarray=originalArray.slice();  
newarray[1].push(100);
//Let's look at the changes in these arrays:
console.log(newarray)
console.log(originalArray)

//output:
[ [ 1, 2, 3 ], [ 4, 5, 100 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 100 ] ]
We can see that when the copy array is changed, the original array will be changed. How to solve this problem? When we learn another method map() will get the answer.

As a programmer, do not modify the original array is a good programming habits. In many Challenge are default or explicitly pointed out: the user should not modify the original array

Ok, lesson is over. let's us do some task.

Task
Coding in function threeInOne. function accept 1 parameters arr, it's a 1D number array. Your task is to merge each of the 3 elements into 1 elements (sum value) and return the result.

Note1: You should not modify the original array.

Note2: Because this is a beginner Challenge, and due to the author's mercy ;-), so you do not have to verify the validity of the parameter, and do not worry about the number of elements of the array is not a multiple of 3.

Example:

threeInOne( [1,2,3]) should return [6]
threeInOne( [1,2,3,4,5,6]) should return [6,15]
threeInOne( [1,2,3,4,5,6,7,8,9]) should return [6,15,24]
threeInOne( [1,3,5,2,4,6,7,7,7]) should return [9,12,21]

bu soruda nereden başlıyacağımı nasıl başlayacağımı bilemiyorum fakat yanımda birisi ne yapmam gerektiğini adım adım anlattığında kolaylıkla yazabiliyorum

The sub-items of the ‘Products’ item in the ‘Menu’ dropdown are not displayed when clicked

The sub-items of the ‘Products’ item in the ‘Menu’ dropdown are not displayed when clicked،

he ‘فهرست’ button works correctly when clicked and opens the dropdown, but when I click on the ‘محصولات’ item, the dropdown closes. I want the sub-items of ‘محصولات’ to be displayed when I click on it.

he ‘فهرست’ button works correctly when clicked and opens the dropdown, but when I click on the ‘محصولات’ item, the dropdown closes. I want the sub-items of ‘محصولات’ to be displayed when I click on it.

Removing eventListener (function with an attribute) in JavaScript [duplicate]

I am working on selection mode in my app (selecting multiple elements to execute some action). It works like this: at default you have a list of elements (decks) which are <a> HTML elements. So, if you click one, it will redirect you to the specific page. There is also a “Select mode” button on the page. After clicking it, redirection is turned off (event.preventDefault), instead selected items are added to an array (selectedDecks) and styling is changed.

The problem is that I do not know how to remove the event listener when I exit selection mode. It still changes the styling etc. instead of redirecting.

Here is the function for toggling between selection mode on/off:

Here is function for toggling between selection mode on/off (I used ‘deck.removeEventListener('click', () => handleDeckClick(event, selectedDecks));‘ here but it does not work):

   function toggleSelectionMode() {
    selectionMode = !selectionMode;
    
    let selectedDecks = [];

    if (selectionMode) {
    selectionModeElements.decks.forEach(deck => {
        deleteSelectedDecksButton.style.transform = "scale(1)"
        deck.style.opacity = "50%";
        deck.addEventListener('click', () => handleDeckClick(event, selectedDecks));
    });
} else {
    selectionModeElements.decks.forEach(deck => {
        deck.removeEventListener('click', () => handleDeckClick(event, selectedDecks));
        deck.style.opacity = "100%";       
        let deckCheck = deck.querySelector(".deck-check");
        deckCheck.style.transform = "scale(0)";
        deck.deckSelection = false;
    });
    selectedDecks = [];
    deleteSelectedDecksButton.style.transform = "scale(0)"; 
}
}

and here is the function for handling clicking a deck (executed as an eventListener):

    function handleDeckClick(event, selectedDecks) {
    event.preventDefault();
    let deck = event.currentTarget;
    let deckCheck = deck.querySelector(".deck-check");
    let deckSelection = deck.deckSelection || false;

    if (deckSelection === false) {
        deck.style.opacity = "100%";
        deckCheck.style.transform = "scale(1)";
        selectedDecks.push(deck.getAttribute('data-deck-id'));
        deck.deckSelection = true;
    } else {
        deck.style.opacity = "50%";
        deckCheck.style.transform = "scale(0)";
        const indexToRemove = selectedDecks.indexOf(deck.getAttribute('data-deck-id'));
        if (indexToRemove !== -1) {
            selectedDecks.splice(indexToRemove, 1);
        }
        deck.deckSelection = false;
    }
}  

Do you have any ideas about what I could use instead of deck.removeEventListener('click', () => handleDeckClick(event, selectedDecks));? Is there a way to simply remove all event listeners from the element without specifying them? Or perhaps I should approach the entire selection mode differently? Thanks for your replies in advance.

html element cloning issue

i’m struggling with one very specific issue…
I have WP plugin for printing price tags and recently on mobile chrome disapeared cloned qr image.
Let overview: first i generate html element (price tag), then i have print button, after pushing it with javascript cloning existing element and open print window, but on cloned element disapears qr image.

tryed to generate new qr image on cloned element, but still nothing. Issue is just on mobile chrome. Tryed to check “desktop version” on mobile chrome, then everything works fine, but it not solves problem. Maybe there are some chrome settings?

Any ideas?

Does updating the source of an image multiple times per second lead to performance issues?

I’m not really sure how to wrap this question in a single sentence, but I’ll explain in as few words as I can.
The landing page for my (work in progress) website is a picture of a building, and you can click on the door to get to a different page. Before the location changes, the source of an image in the page changes every 33 ms in order to simulate a 30fps animation.
This is in my .blade.php file (I’m using Laravel 11):

    <div class="d-none d-lg-block">
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            viewBox="0 0 1920 1080" id="landingSvg">
            <image width="1920" height="1080" xlink:href="/media/frames/1.jpg" id="landingImage"></image>
                <rect x="599" y="678" fill="#fff" opacity="0" width="136" height="261" id="door"></rect>
        </svg>
    </div>

While this is the Javascript that handles the animation (I’m using jQuery):

$(document).ready(function(){
    $("#door").click(() => {
        //Hiding the door element
        $("#door").hide();
        //Initializing frame count as 2
        let i = 2;
        //Using an interval to change the image url every 33 milliseconds, simulating a 30fps animation
        let frames = setInterval(() => {
            //Changing the image url of the main background to the next frame
            $("#landingImage").attr("xlink:href", `/media/frames/${i}.jpg`);
            //Increasing the frame count
            i++;
            //Checking if the counter has reached the value of 31, as in that case there will be no more frames to load
            if (i >= 31) {
                clearInterval(frames);
                //Changing position to the next page after 700 milliseconds
                setTimeout(() => {
                    window.location.assign('http://localhost:8000/reception');
                }, 700)
            }
        }, 33)
    }
)
// $(document).ready() ends here
})

I tested this on my local machine and it works fine. I rarely get some frame skipping, but almost always the animation is very smooth.
Now, this is what I was wondering: when I eventually ship the application to production, playing the animation means requesting a fairly large image (1920×1080) every 33 ms from a server that is possibly fairly distant from the user; will the server be able to perform this operation as smoothly? If not, what can I do to solve the issue?
Thanks in advance.

How can I use Office JS add-in to track the coordinates of a shape in PowerPoint?

When I use Office JS (JavaScript API for Office) add-in to track the coordinates of a shape in PowerPoint as it moves but I didn’t get any coordinates over slides, I guess we can use the Office JavaScript API to interact with PowerPoint, but Office JS currently doesn’t directly support mouse event listeners for shapes.

I’m developing a PowerPoint add-in using Office JS, and I need to track the coordinates of a shape on a slide as it moves. Specifically, I want to capture and log the position of a shape whenever it’s moved or resized.

I understand that Office JS provides APIs to interact with shapes and slides, but I’m not sure how to continuously track the position of a shape in real-time or how to get updated coordinates when the shape is moved.

Could someone provide guidance or examples on how to achieve this with Office JS? For instance, how can I get the position of a shape after it has been moved or resized, and how can I set up an event or mechanism to track these changes?