Make javascript/jQuery script run after the sidebar loads dynamically

I’m trying to bulk upload a video on multiple WordPress websites at once by just uploading the video on a server.

Everything is working fine except the video doesn’t load on single post’s sidebar.

The idea is that the video loads on many websites at once only when we have a video available on the server and when there’s no video available the video player hides, that’s why the video is hidden at first and then get’s visible via the script only when there’s no error on the video player.

The time() function is used to tackle the cache issue.

The script is unable to execute in single post’s sidebar only (where I actually want the video to show), as the video is getting loaded on Homepage’s sidebar and even after the content on single posts perfectly.

Code is placed using the plugin Advanced Ads and placed via it’s widget on both sidebars (Homepage sidebar and Sidebar for Posts).

Here’s the code –

<video id="video" width="100%" height="auto" poster="https://webtik.in/ads/cover.jpeg?nocache=<?php echo time(); ?>" controls style="display: none;">
  <source id="videoSource" src="https://webtik.in/ads/video.mp4?nocache=<?php echo time(); ?>" type="video/mp4">
</video>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const checkAndInitializeVideo = () => {
    const video = document.getElementById('video');
    const videoSource = document.querySelector('#video source');

    if (video && videoSource) {
      video.addEventListener('loadedmetadata', () => {
        video.style.display = 'block';
      });

      video.addEventListener('error', () => {
        video.style.display = 'none';
      });

      videoSource.addEventListener('error', () => {
        video.style.display = 'none';
      });
    }
  };

  checkAndInitializeVideo();

  const sidebar = document.querySelector('#secondary');
  if (sidebar) {
    const observer = new MutationObserver(() => {
      checkAndInitializeVideo();
    });

    observer.observe(sidebar, { childList: true, subtree: true });
  }
});
</script>

After Googling a bit I came to know that the sidebar is loading dynamically on single pages, hence the script is not getting executed. Any fix for this?

Afficher des tâches spécifiques à chaque titre dans une to-do list en JavaScript [closed]

Je travaille sur une to-do list où chaque titre (catégorie) a ses propres tâches. Par exemple, les tâches sous ‘Jouer’ ne doivent pas apparaître si je sélectionne ‘Manger’, et vice versa. J’ai essayé plusieurs solutions : réinitialiser la div des tâches avec reset(), utiliser display: none, filtrer les tâches par tableau pour chaque titre, et transformer mes listes de tâches en un objet où chaque clé est un titre avec un tableau de tâches. Tout fonctionne sauf l’affichage : les tâches associées à un titre apparaissent a chaque fois sur d’autres mais par contre le formulaire est réinitialisé lorsque j’appuis sur d’autre titre. Pourtant, le comptage des tâches par titre est correct. Des idées pour résoudre ce problème d’affichage ?

J’ai essayé réinitialiser la div contenant les tâches avec une fonction reset() à chaque changement de titre.
Utiliser display: none pour cacher les tâches des autres titres.
Filtrer les tâches via un tableau associé à chaque titre.
Représenter mes listes de tâches comme un objet, où chaque clé est un titre associé à un tableau de tâches.
Ce que je m’attendais à obtenir :
Que seules les tâches associées au titre sélectionné s’affichent, sans interférer avec celles des autres titres.

Ce qui s’est réellement passé :
Malgré ces tentatives, certaines tâches d’un titre apparaissent dans un autre. En revanche, le comptage des tâches par titre fonctionne correctement.

“The resource cannot be found” when invoking WCF service with HTTPS

We have a webpage (HTTP:||www.MySite.com/Map/Dashboard.html) that shows some static content and a javascript chart that invokes this WCF: HTTP:||www.MySite.com/Map/Map.svc/GetData/01-01-2023/01-12-2023/1.

This has been working great so far: the static content is displayed and the javascript chart is rendered because the service (being invoked directly with http) will return the expected JSON.

Recently, I installed an SSL certificate to the domain, so when the WCF call is made under HTTPS, I get the error “The resource cannot be found.” (HTTP 404).

In other words, when I go to HTTPS:||www.MySite.com/Map/Dashboard.html it returns the static content of the page, but the javascript chart is not rendered because it’s invoking HTTPS:||www.MySite.com/Map/Map.svc/GetData/01-01-2023/01-12-2023/1, which returns a 404 error “The resource cannot be found.”

I only have the web.config, but not the source code.

In our js javascript library, I specifically build the WCF call with the “http” protocol but it seems it’s being forced to redirect as “https” since (I assume) the initial html is also https.

Without having the source code, what would I need so that the WCF call also functions with https?

If this is not an option, is it possible to configure web.config (or the web host) to not force the WCF to “https” even though the html is https?

Streamlit scrolling to end page

The task is to scroll down the page when you click on the button in streamlit.
It describes how this can be implemented, but it doesn’t work
https://discuss.streamlit.io/t/how-can-i-use-an-auto-scroll-to-the-bottom-of-the-page/39650/10
I try this:

                st.session_state['dummy_counter'] += 1
                st.markdown(
                    """
                    <div id="end"></div>
                    """,
                    unsafe_allow_html=True
                )
                st.components.v1.html(f"""
                    <script>
                        console.log('check');
                        var count = {st.session_state['dummy_counter']};
                        var element = document.getElementById("end");
                        if (element)  {{
                            element.scrollIntoView({{behavior: "smooth"}});
                            console.log('check2');
                        }}
                    </script>
                """,height=1)

When executing the code in the browser, scrolling occurs, but streamlite does not work.
I want to scroll the page to the end element, when I output it in the console, the end element will find it, but in the streamlit’e at the stage

var element = document.getElementById ("end"); 

returns element = null. in browser:

<div id="end"></div>

I set the timer, it is clearly visible that this is not due to page loading. Perhaps there is a simpler solution? Or how to fix mine? Thanks

Angular Init two services that depends on each other

I have Database service that reads data from IndexedDB using RxDB library and has initDatabase function to initialize it.

@Injectable({
  providedIn: 'root',
})
export class DatabaseService {
  private static database: MyDatabase;

  constructor() {}

  async initDatabase(): Promise<void> {
    console.log('Initializing database');
    if (!DatabaseService.database) {
      const db = await createRxDatabase<MyDatabaseCollections>({
        name: 'mydb',
        storage: getRxStorageDexie(),
      });

      await db.addCollections({
        items: {
          schema: itemSchema,
        },
        baseUnits: {
          schema: baseUnitSchema,
        },
        brands: {
          schema: brandSchema,
        },
        contacts: {
          schema: contactSchema,
        },
        suppliers: {
          schema: SupplierSchema,
        },
      });

      DatabaseService.database = db;
    }
  }

  getDatabase(): MyDatabase {
    if (!DatabaseService.database) {
      throw new Error('Database not initialized yet');
    }
    return DatabaseService.database;
  }
}

And Items service that depends on the Database service by initItemsService function

@Injectable({
  providedIn: 'root',
})
export class ItemsService {
  private itemsSubject = new BehaviorSubject<ItemType[]>([]);
  private itemSearchTermSubject = new BehaviorSubject<string>('');

  public items$;
  public searchTerm$;

  constructor(private databaseService: DatabaseService) {
    this.items$ = this.itemsSubject.asObservable();
    this.searchTerm$ = this.itemSearchTermSubject.asObservable();
  }

  setItems(items: ItemType[]) {
    this.itemsSubject.next(items);
  }

  getItems(): ItemType[] {
    return this.itemsSubject.getValue();
  }

  setItemSearchTerm(term: string) {
    this.itemSearchTermSubject.next(term);
  }

  getItemSearchTerm(): string {
    return this.itemSearchTermSubject.getValue();
  }

  findItemsByName(name: string): ItemType[] {
    return this.itemsSubject
      .getValue()
      .filter((item) => item.name.toLowerCase().includes(name.toLowerCase()));
  }

  initItemsService() {
    this.databaseService
      .getDatabase()
      .items.find()
      .$.subscribe((docs) => {
        this.setItems(docs);
      });
  }
}

Finally initializing both services inside app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAnimations(),
    MessageService,
    DatabaseService,
    provideAppInitializer(() => inject(DatabaseService).initDatabase()),
    provideAppInitializer(() => inject(ItemsService).initItemsService()),
  ],
};

But the database is not yet initialized by the time Item reads it getting error:

Database not initialized yet

Which is the error in funcrion getDatabase()

Cefsharp, fetch request gets blocked when mouse and keyboard events are firing

I’m using Three.js to render a 3D scene in my web application. After each rendering frame, I send a request to the server to see if any 3D objects have changed position. This is working as expected for smaller scenes. However, with a larger scene that’s more demanding on the rendering process, I’m running into an issue. When I press a key on the keyboard and move the mouse simultaneously, the server stops responding to my requests. I haven’t set up any event listeners for keyboard input in my JavaScript code, and the mouse is only used to control the camera.

enter image description here

When I use the Performance Tool in Chromium, I see that the keyboard is taking up a lot of view time. I don’t understand why I have so much delay and if it’s completely blocking my fetch response.

I created my own IKeyboardHandler for CefSharp, hoping that it would prevent keyboard events from being triggered. However, this didn’t work.

I lowered the FPS to 30.

Memory Leak Caused by Clicking a Cell and Destroying an HTML Table, Resulting in Increased DOM Nodes

Issue Description

We are facing a memory leak issue When destroying the HTM Table after performing a mouse click action in its cell. This behavior could indicate improper element removal or unnecessary node creation, potentially impacting performance and causing unintended functionality.

https://github.com/hemanthkumar-syncfusion/html-table
https://github.com/hemanthkumar-syncfusion/html-table/issues/1

DOM Nodes Count:

Initial

After rendering the table and clicking on any cell

After destroying the table

I checked the issue in both Edge and Chrome, and was able to observe the element in a detached state. I was also able to reproduce the same memory issue in both the HTML input and button. I checked the event listeners for those elements but was unable to find the cause.

Replication Procedure:

  1. Run the sample.
  2. Check the initial DOM node in the performance monitor tab after garbage collector in the memory tab.
  3. Click the Create Table Button.
  4. Click any one of cells.
  5. Click the Destroy Button to destroy the table.
  6. Now check the DOM Node count in the performance monitor tab.

Question:

  1. How to resolve this memory leak issue?
  2. I also observed that each time a cell is clicked, the number of JavaScript event listeners seems to increase. Could you kindly explain why this is happening?

How can I connect to weather on a site? [closed]

In an agricultural project, I want to add the weather forecast and send feedback to the user. For example: “The weather is sunny tomorrow, it’s time to plant your crops.” How can a system be made that will give propositions like this? If you explain this with html/js/css code, it would be much easier for us, and it would be great if you helped this project, because we worked hard to do this, we even asked for data from meteorology, but they turned us down :)))

Repositioning and activating image view does not work as expected

I am trying something with the help of JavaScript in which when we click on a card image, the image inside the card should move to the left and another div should get activated which contains the content. Suppose I want to click on the 3rd card image then this 3rd card’s image should be moved to left:0 or you can say over the 1st card image and inside the 3rd card image’s div should get activated which contains the content.

You can understand this with the help of images of what I want-

Original look

What I want

const cards = document.querySelectorAll(".card");

cards.forEach(card => {
  card.addEventListener("click", () => {
    const details = card.querySelector(".details");
    const img = card.querySelector(".card_img");
    details.classList.toggle("active_details");
    img.classList.toggle("active_img");
  });
});
.team_main_container {
  border: 2px solid red;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.team_main_container .team_cards_container {
  border: 2px solid green;
  width: 90%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

.team_main_container .team_cards_container .card_section {
  border: 2px solid red;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  /* display: grid;
    grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr)); */
  gap: 20px;
}

.team_main_container .team_cards_container .card_section .card {
  /* width: 100%;
    height: auto; */
  width: calc((100% / 5) - 16px);
  height: 30rem;
  cursor: pointer;
  border: 2px solid red;
  position: relative;
}

.team_main_container .team_cards_container .card_section .card .card_img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.team_main_container .team_cards_container .card_section .card .shot_det {
  border: 2px solid green;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #93310c;
  opacity: 0;
  transition: 0.3s ease-in-out;
}

.team_main_container .team_cards_container .card_section .card:hover .shot_det {
  opacity: 1;
}

.team_main_container .team_cards_container .card_section .card .details {
  display: none;
}

.team_main_container .team_cards_container .card_section .card .details.active_details {
  border: 2px solid green;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  color: #fff;
  background-color: #26252a;
  transition: 0.3s ease-in-out;
}

.team_main_container .team_cards_container .card_section .card .card_img.active_img {
  transform: translate(-212.2%);
}
<div class="team_main_container">
  <div class="team_cards_container">
    <div class="card_section">
      <div class="card">
        <img src="../images/img.jpg" alt="card 1" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 1</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 2" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 2</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 3" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 3</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 4" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 4</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 5" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 5</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 6" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 6</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 7" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 7</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 8" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 8</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 9" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 9</p>
        </div>
      </div>

      <div class="card">
        <img src="../images/img.jpg" alt="card 10" class="card_img">
        <p class="shot_det">Lorem ipsum dolor, sit amet consectetur adipisicing elit</p>
        <div class="details">
          <p class="lon_det">Card 10</p>
        </div>
      </div>
    </div>
  </div>
</div>

why the background color is not changing

ok so Like I wrote code to change the color of the background

function updatePlaylistHeaderColor() {
    const imgEl = document.getElementById('playlist-header-img');
    imgEl.crossOrigin = 'Anonymous'; // Set crossOrigin attribute
    const dominantColor = getDominantColor(imgEl);
    document.getElementById('playlist-header').style.backgroundColor = dominantColor;
}

It works fine when the intial image is loaded

document.getElementById('playlist-header-img').addEventListener('load', updatePlaylistHeaderColor);

But doesnt work when I change the src of img tag and then call it like

document.getElementById('playlist-header-img').src = playlist.images[0].url;
updatePlaylistHeaderColor();

TonConnect sendTransaction – mobile app issue

I have implemented the connection of the user’s wallet to the site via TonConnect ui
The user connects, specifies the amount he wants to invest in the project, sends a request – on desktop and web the request comes perfectly, everything works, but for example in tonkeeper mobile application the request comes and disappears immediately. I suspect that it’s the signature, but I can’t figure out how to do it. Here is the code of sending, as far as I understand, I need before
await tonConnectUI.sendTransaction(transaction, { modals: ['before', 'success', 'error'], notifications: ['before', 'success', 'error'] });

send a request for a signature, but I don’t understand at all how this is set up and should be, and the documentation is totally confusing to me( Please help me to achieve a successful request on mobile apps.

`
 const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
 manifestUrl: 'https://example.com/tonconnect-manifest.json',
 buttonRootId: 'ton-connect'

});

async function initiateTransaction(amount) {


 var sm = amount;

 const recipientAddress = 'UQDVqo3lguMUvPwdD6xk7lMz3g_cHFFMhnEO6hI1n2XXLt0I';  
const transaction = {
   validUntil: Math.floor(Date.now() / 1000) + 360,
    messages: [
        {
          address: recipientAddress,
            amount: (amount * 1000000000).toString()  
        }
    ]
};

  try {
    const currentAccount = tonConnectUI.account;
    let json = JSON.stringify(currentAccount);
    var myObj = JSON.parse(json);
    const ad = myObj['address'];
    const nacl = TonWeb.utils.nacl;
    const tonweb = new TonWeb();
    const keyPair = nacl.sign.keyPair();
    let secretKey = keyPair.secretKey;
    let wallet = tonweb.wallet.create({
        publicKey: keyPair.publicKey
    });
    wallet = tonweb.wallet.create({
        address: ad
    });
    secretKey = TonWeb.utils.hexToBytes('1209645867598672398567298346723894769879');
    const address = await wallet.getAddress();
    const address_o = address.toString(true, true, true, false);         

     
  //  $.ajax({
  //       url: "/handler_transaction.php",
  //       type: "post",
  //       dataType: "json",
  //       data: {
  //           "adt": address_o,
        //          "sm": sm,

  //       },
  //       success: function(data) {
       
  //       }
  //   });       
     



    // Отправляем транзакцию с подписанием через TON Connect UI
    const result = await tonConnectUI.sendTransaction(transaction, {
        modals: ['before', 'success', 'error'],  // Модальные окна для отображения        статуса
        notifications: ['before', 'success', 'error']  // Оповещения о статусе
    });

    const someTxData = await myAppExplorerService.getTransaction(result.boc);
    console.log('Текст boc ', someTxData);
    console.log('Транзакция отправлена', result);

    if (result.success) {
        console.log('Транзакция успешно выполнена');
        // const walletInfo = await tonConnectUI.getWalletInfo();
        // const walletAddress = walletInfo.account.address;
        // await updateStaking(walletAddress, amount);
        alert('Транзакция успешно отправлена');
    } else {
        console.error('Транзакция не удалась', result.errorMessage);
        alert('Ошибка отправки транзакции: ' + result.errorMessage);
    }
} catch (error) {
    console.error('Ошибка при отправке транзакции', error);
    alert('Ошибка отправки транзакции: ' + error.message);
}
}`

I’ve tried everything I can think of, but I’m exhausted.

What is a restricted JavaScript object?

I’m trying to use custom DOM events to communicate between the main world and the isolated world for a page in a webextension in Firefox. When trying to access an event object property, I get an access denied error. Most of what follows is just context. I really want to know what a “restricted” object is.

listener

function onCustom( e ) {
  console.log( e );
  console.log( e.detail );
  console.log( e.detail.plugh );
}
document.addEventListener( 'custom', onCustom );

sender

e = new CustomEvent( 'custom', { detail: {
  plugh: 'xyzzy'
} } );

document.dispatchEvent( e );

If the listener and the sender are both in the same world, it works fine. (This case is just a sanity check, since the point is to communicate between worlds.)

If the listener is in the isolated world and the sender is in the main world, it works fine.

If the listener is in the main world and the sender is in the isolated world, it pukes as follows.

console output

custom { blah, blah, blah, lots of properties }
Object { plugh: "xyzzy" }
Uncaught Error: Permission denied to access property "plugh"

I can expand the Object (second line) in the devtools console. It’s there.

If I expand the “custom” object (first line) in the devtools console, it says (in part):

  detail: Restricted {  }

The detail property of a CustomEvent can be anything serializable. I can do my own serialization with JSON.stringify in the sender and deserialize it with JSON.parse in the listener. It’s annoying, but it’s a workaround that does work. I still want to know what’s going on with the object that I cannot access it after it was serialized and deserialized transparently for me.

require() inside or outside module.exports

It’s about using require() and re-export it in the index.js.

For me i always adding the require() in the top of the file like that:

const DocumentService = require('./document.service');

module.exports = {
    DocumentService
};

But currently i’m working on some legacy code, which look like that:

module.exports = {
    DocumentService: require('./document.service')
};

I can see an advantage with the first implementation is that it works better with my editor. When i use the function Go to Declaration of my editor it goes to the imported file. By the second implementation, it only goes to the index.js.

The question what would be the best implementation for doing re-export like that? Is there any difference on performance or initialization of the object during the runtime?

How to add/change a script’s value dynamically in the head tag? [closed]

I am trying to add the below script in my html head section.

<script type="text/javascript" lang="javascript" src="www.example.com/js/script.js?apikey=<YOUR_SITE_APIKEY>">
    {
        verifyLoginInterval: 1 // hour
    }
</script>

I’m trying to achieve this with the following code:

var script = document.createElement('script');
script.type = 'text/javascript';
script.lang = 'javascript'
script.src = "https://www.example.com/js/script.js?apiKey=XYZ"
script.innerHTML="{verifyLoginInterval: 60}";
var headElement = document.head.lastChild;
headElement.parentNode.insertBefore(script, headElement);

I am getting the script in the head section with desire code.
But i just wanted to check. is this the right way to add script code in the page.

can someone help here?

error TS2550: Property ‘any’ does not exist on type ‘PromiseConstructor’

**

Code :
async function fetchDataWithDelay(delay: number, data: string) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(data), delay);
});
}

async function fetchAnyData() {
  try {
    const result = await Promise.any([
      fetchDataWithDelay(3000, "Data 1"),
      fetchDataWithDelay(1000, "Data 2"),
      fetchDataWithDelay(2000, "Data 3"),
    ]);
    console.log("First resolved data:", result);  // "Data 2"
  } catch (error) {
    console.error("Error:", error);
  }
} fetchAnyData();

**

error TS2550: Property ‘any’ does not exist on type ‘PromiseConstructor’. Do you need to change your target library? Try changing the ‘lib’ compiler option to ‘es2021’ or later.
I had already given the lib as given below

lib: [“es2021″,”dom”]

Node version is v22.8.0,
tsc version 5.7.2
ide is vs code
still getting the same error in terminal with cmd

Can anyone suggest