HTML Snippet not loading Js code.

0
Some widgets are shifting the focus to the top of the page when clicking enter so i added HTMLSnippet in the page to detect the click and change the focus to the desired element but the HTML snippet does not work as expected. Here is the code:  function ImageControl(){    console.warn("Dom Content Loaded");    let paginationBar = document.querySelector('.pagination-bar');    console.warn("paginationBar");    let children = paginationBar.children;    for (let i = 0; i < children.length; i++) {      let currentIndex = i;       children[i].addEventListener('click', function(event) {        if (currentIndex == 0) {          const timeout1 = setTimeout(()=>{           children[3].focus();           }, 600);        } else if (currentIndex == 4) {          const timeout1 = setTimeout(()=>{           children[0].focus();           }, 600);        } else {          children[currentIndex].focus();        }      });    }  }const timeout = setTimeout(()=>{   ImageControl();}, 10000);
asked
1 answers
0

Hey Tejaswi,

You need to ensure the DOM elements are available when the script runs. The setTimeout you used might not always be reliable. Also make sure the paginationBar and its children are correctly selected. Finally, make sure that event listeners are correctly attached to the elements.

 

Try to use this code:

document.addEventListener("DOMContentLoaded", function() {
    function ImageControl() {
        console.warn("DOM Content Loaded");
        
        let paginationBar = document.querySelector('.pagination-bar');
        if (!paginationBar) {
            console.warn("Pagination bar not found.");
            return;
        }
        
        console.warn("Pagination bar found.");
        let children = paginationBar.children;
        
        for (let i = 0; i < children.length; i++) {
            let currentIndex = i;
            
            children[i].addEventListener('click', function(event) {
                if (currentIndex === 0) {
                    setTimeout(() => {
                        children[3].focus();
                    }, 600);
                } else if (currentIndex === 4) {
                    setTimeout(() => {
                        children[0].focus();
                    }, 600);
                } else {
                    children[currentIndex].focus();
                }
            });
        }
    }

    // Ensure ImageControl is called after DOM is fully loaded
    setTimeout(() => {
        ImageControl();
    }, 1000); // Adjust timeout if necessary
});

 

This code may not complety solve your issues but it should help :)

 

If this answer helped, mark as "accepted"

 

Best Regards,

Ricardo Pereira

answered