0

I have simple code which will automatically scroll the slider horizontaly from begining to end and then the reverse.

Code working fine when I type it to the loaded site to console but when I add it to my Javascript which HTML of this slider inserting to homepage dynamicaly.

I think some issues may be in this script but I really dont know where.

Thanks for all help

ERROR MESSAGE: here

SCRIPT:

var logosIndustry = document.querySelector(".logos");
        function move() {
        logosIndustry.scrollLeft += 1;
        if(logosIndustry.scrollLeft >= (2600 - logosIndustry.offsetWidth)){
            clearInterval(interval);
            interval = setInterval(moveReverse,5);
        }
        }
        function moveReverse() {
        logosIndustry.scrollLeft -= 1;
        if(logosIndustry.scrollLeft <= 0){
            clearInterval(interval);
        }
        }
        interval = setInterval(move, 5)
jozo Jozo
  • 57
  • 5

1 Answers1

0

Your script runs before the .logos element is in the DOM.

Try running it after the DOM is ready.

var logosIndustry;
var interval;

function move() {
  logosIndustry.scrollLeft += 1;
  if (logosIndustry.scrollLeft >= (2600 - logosIndustry.offsetWidth)) {
    clearInterval(interval);
    interval = setInterval(moveReverse, 5);
  }
}

function moveReverse() {
  logosIndustry.scrollLeft -= 1;
  if (logosIndustry.scrollLeft <= 0) {
    clearInterval(interval);
  }
}

window.addEventListener('DOMContentLoaded', () => {
  logosIndustry = document.querySelector(".logos");
  interval = setInterval(move, 5);
});
Gabriele Petrioli
  • 173,972
  • 30
  • 239
  • 291