Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function createInfiniteImageMarquee(selector, options = {}) {
- // Find parent element
- const parentElement = document.querySelector(selector)
- // default options
- const {
- height = "200px",
- gap = 0,
- speed = 2000
- } = options
- // parent styles
- parentElement.style.maxWidth = '100%'
- parentElement.style.overflowX = 'hidden'
- parentElement.style.minHeight = height
- parentElement.style.position = 'relative'
- // get image elements and urls
- const images = [...parentElement.querySelectorAll(':scope > img')]
- const urls = images.map(img => img.src)
- const length = images.length
- const imgWidth = 100/(length-1)
- // delete contents
- parentElement.innerHTML = ""
- const createImg = (i, start = i) => {
- // Define element and attributes
- const img = document.createElement('img')
- img.classList.add('marquee-img')
- const url = urls[i]
- img.src = url
- // Styles
- img.style.height = height
- img.style.width = imgWidth + "%"
- img.style.objectFit = "cover"
- img.style.position = 'absolute'
- img.style.top = '0px'
- const leftMargin = gap * start
- img.style.left = `calc(${(imgWidth*start) + '%'} + ${leftMargin}px)`
- const transition = speed * (start+1)
- img.style.transition = transition + 'ms linear'
- // append to parent
- parentElement.append(img)
- // move
- requestAnimationFrame(() => {
- // Simply accessing this property forces the browser to re-register the image's position?
- // I'm not sure why
- img.offsetWidth
- img.style.left = (-imgWidth) + '%'
- setTimeout(() => {
- createImg(i, length-1)
- img.remove()
- }, transition);
- })
- }
- // start
- for (let i = 0; i < length; i++) {
- createImg(i)
- }
- }
- // TEST
- createInfiniteImageMarquee('.image-marquee', {
- height: '300px',
- gap: 20
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement