Last active
January 31, 2024 17:26
-
-
Save inerba/1d9a7ed1071cf23f93bdd45074a7e3cf to your computer and use it in GitHub Desktop.
Horizontal scrolling on a specified element with mouse wheel
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
/** | |
* This function enables horizontal scrolling on a specified element when the mouse wheel is used. | |
* @param {string} selector - The CSS selector of the element on which to enable horizontal scrolling. | |
* @param {number} scrollValue - The amount to scroll each time the mouse wheel is used. Defaults to 100. | |
* @param {number} extraScroll - The number of times to allow scrolling past the end of the element. Defaults to 5. | |
* @returns {void} | |
*/ | |
export let horizMouseScroll = ( | |
selector, | |
scrollValue = 100, | |
extraScroll = 5, | |
) => { | |
const scrollContainer = document.querySelector(selector); | |
if (!scrollContainer) | |
return console.error(`No element found for selector "${selector}"`); | |
let scrollCount = 0; | |
scrollContainer.addEventListener("wheel", (evt) => { | |
const scrollAmount = evt.deltaY > 0 ? scrollValue : -scrollValue; | |
scrollContainer.scrollLeft += scrollAmount; | |
if ( | |
scrollContainer.scrollWidth - | |
scrollContainer.scrollLeft - | |
scrollContainer.clientWidth > | |
0 && | |
scrollContainer.scrollLeft > 0 | |
) { | |
evt.preventDefault(); | |
scrollCount = 0; | |
} else { | |
scrollCount++; | |
if (scrollCount < extraScroll) { | |
evt.preventDefault(); | |
} | |
} | |
}); | |
}; |
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
// Other imports | |
import { horizMouseScroll } from "./horizMouseScroll"; | |
window.horizMouseScroll = horizMouseScroll; |
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
<div id="courses-carousel" class="flex lg:flex-nowrap snap-x snap-proximity relative overflow-x-scroll"> | |
<!-- long list of stuff --> | |
</div> | |
<script> | |
document.addEventListener('DOMContentLoaded', function () { | |
horizMouseScroll('#courses-carousel', 200, 10); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment