Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67469

How can I scroll left and right smoothly on an element by triggering an event on a button?

$
0
0

How can I scroll left and right smoothly on an element by triggering an event on a button using JavaScript? (no jQuery) So I want to click on the next and back buttons and scroll left or right on the my-container__content which has really long content within.

Trying the below doesn't seem to work

HTML

<div class="my-container">
    <div class="my-container__content" style="overflow-x: scroll;" data-scroll-container>
        <div class="my-container__item" width="1000000000px">

        </div>
    </div>
<div>

<button data-back data-scroll-trigger>Back</button>
<button data-next data-scroll-trigger>Next</button>

JS

/**
 * Selectors
 */
const selectors = {
    scrollContainer: '[data-scroll-container]',
    scrollTrigger: '[data-scroll-trigger]',
    scrollNext: 'data-next',
    scrollBack: 'data-back',
};

/**
 * Main
 */

const scrollTrigger = [...document.querySelectorAll(selectors.scrollTrigger)];
const scrollContainer = document.querySelector(selectors.scrollContainer);


const handleScroll = ({ target }) => {
    if (target.hasAttribute(selectors.scrollBack)) {
        scrollContainer.scrollTo({
            right: 100,
            behavior: 'smooth',
        });
    } else {
        scrollContainer.scrollTo({
            right: 100,
            behavior: 'smooth',
        });
    }
};


if (scrollTrigger) {
    scrollTrigger.forEach((scroll) => {
        scroll.addEventListener('click', handleScroll);
    });
}


Viewing all articles
Browse latest Browse all 67469

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>