Advertisement
dugalcedo

Marquee-JS

May 28th, 2025
665
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function createInfiniteImageMarquee(selector, options = {}) {
  3.     // Find parent element
  4.     const parentElement = document.querySelector(selector)
  5.  
  6.     // default options
  7.     const {
  8.         height = "200px",
  9.         gap = 0,
  10.         speed = 2000
  11.     } = options
  12.  
  13.     // parent styles
  14.     parentElement.style.maxWidth = '100%'
  15.     parentElement.style.overflowX = 'hidden'
  16.     parentElement.style.minHeight = height
  17.     parentElement.style.position = 'relative'
  18.  
  19.     // get image elements and urls
  20.     const images = [...parentElement.querySelectorAll(':scope > img')]
  21.     const urls = images.map(img => img.src)
  22.  
  23.     const length = images.length
  24.     const imgWidth = 100/(length-1)
  25.  
  26.     // delete contents
  27.     parentElement.innerHTML = ""
  28.  
  29.     const createImg = (i, start = i) => {
  30.         // Define element and attributes
  31.         const img = document.createElement('img')
  32.         img.classList.add('marquee-img')
  33.         const url = urls[i]
  34.         img.src = url
  35.  
  36.         // Styles
  37.         img.style.height = height
  38.         img.style.width = imgWidth + "%"
  39.         img.style.objectFit = "cover"
  40.         img.style.position = 'absolute'
  41.         img.style.top = '0px'
  42.         const leftMargin = gap * start
  43.         img.style.left = `calc(${(imgWidth*start) + '%'} + ${leftMargin}px)`
  44.         const transition = speed * (start+1)
  45.         img.style.transition = transition + 'ms linear'
  46.    
  47.         // append to parent
  48.         parentElement.append(img)
  49.  
  50.         // move
  51.         requestAnimationFrame(() => {
  52.             // Simply accessing this property forces the browser to re-register the image's position?
  53.             // I'm not sure why
  54.             img.offsetWidth
  55.  
  56.             img.style.left = (-imgWidth) + '%'
  57.             setTimeout(() => {
  58.                 createImg(i, length-1)
  59.                 img.remove()
  60.             }, transition);
  61.         })
  62.     }
  63.  
  64.     // start
  65.     for (let i = 0; i < length; i++) {
  66.         createImg(i)
  67.     }
  68. }
  69.  
  70.  
  71. // TEST
  72. createInfiniteImageMarquee('.image-marquee', {
  73.     height: '300px',
  74.     gap: 20
  75. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement