Last active
October 21, 2020 19:43
-
-
Save tttimur/4b0de9cdc6e66ca4fdfd276b1e6c674e to your computer and use it in GitHub Desktop.
Marquee!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style lang="scss"> | |
.carousel { | |
width: 100vw; | |
overflow: hidden; | |
.carousel-animation { | |
width: 50000px; | |
overflow: visible; | |
&.ready { | |
animation: 10s carousel linear infinite; | |
} | |
} | |
.carousel-img { | |
height: 400px; | |
padding-right: 2rem; | |
img { | |
width: auto; | |
height: 100%; | |
} | |
} | |
} | |
@keyframes carousel { | |
from { | |
transform: translateX(-50%); | |
} | |
to { | |
transform: translateX(0); | |
} | |
} | |
</style> | |
<div class="carousel"> | |
<div class="carousel-animation x xw"> | |
<div class="carousel-img carousel-item"> | |
<img src="img.jpg" /> | |
</div> | |
</div> | |
</div> | |
<script> | |
function setupMarquee(selector) { | |
// get all marquee elements | |
document.querySelectorAll(selector).forEach(function (el, index) { | |
// clone children a few times | |
cloneChildren(el) | |
cloneChildren(el) | |
cloneChildren(el) | |
// set up full width | |
setProperSizeForMarquee(el) | |
// setup scrolling class | |
el.classList.add('ready') | |
window.addEventListener('resize', function () { | |
setProperSizeForMarquee(el) | |
}) | |
}) | |
} | |
// get the maximum width of all the children | |
function setProperSizeForMarquee (parent) { | |
let width = 0 | |
parent.childNodes.forEach(function (child) { | |
if (child.nodeName == "#text" || !child.offsetWidth) return false | |
width += child.offsetWidth | |
}) | |
parent.style.width = width + "px" | |
} | |
function cloneChildren (parent) { | |
parent.childNodes.forEach(function (child) { | |
if (child.nodeName == "#text") return false | |
parent.appendChild(child.cloneNode(true)) | |
}) | |
} | |
document.addEventListener('DOMContentLoaded', function () { | |
setupMarquee('.carousel-animation') | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment