Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal Scroll Using Buttons in VueJS

I'm looking to achieve horizontal scroll using buttons in VueJS. I have a container which has several divs stacked horizontally and I want to scroll through them using the buttons.

Here is an identical thread on SO for JQuery. This demo is the solution in JQuery. It should illustrate the effect I'm after.

How can I achieve that effect using VueJS?

Some libraries I have already taken a look at include vue-scroll-to and jump.

  • Vue-scroll-to requires the user to specify an element to scroll to whereas I want to horizontally scroll within a specific element by a set amount of pixels.

  • Jump allows one to scroll over a defined amount of pixels but only works vertically and appears to only scroll on the window.

EDIT: I found a little library that accomplishes this in VanillaJS: https://github.com/tarun-dugar/easy-scroll

like image 847
p4t Avatar asked Jul 07 '18 10:07

p4t


2 Answers

I made a sandbox for this: see it here

The logic is this:

scroll_left() {
  let content = document.querySelector(".wrapper-box");
  content.scrollLeft -= 50;
},
scroll_right() {
  let content = document.querySelector(".wrapper-box");
  content.scrollLeft += 40;
}

You have a wrapper and you increasing/decreasing the scrollLeft property

The full code can be found here

like image 141
Roland Avatar answered Oct 01 '22 23:10

Roland


You can use JavaScript only, using the example you gave I converted it to JavaScript only and here's the Codepen for it.

https://codepen.io/immad-hamid/pen/yEmayr

This is the JavaScript that can replace the example that you sent.

const rightBtn = document.querySelector('#right-button');
const leftBtn = document.querySelector('#left-button');
const content = document.querySelector('#content');

rightBtn.addEventListener("click", function(event) {
  content.scrollLeft += 300;
  event.preventDefault();
});

leftBtn.addEventListener("click", function(event) {
  content.scrollLeft -= 300;
  event.preventDefault();
});

For the animation you have to use something... Can you do that?

like image 29
Immad Hamid Avatar answered Oct 02 '22 01:10

Immad Hamid