Creating a vertical slider on a touch screen

Posted on: by

Creating an element that slide vertically on a touch screen poses a unique problem. When you touch the element, the page intercepts and moves instead of the element you want to move.

So In order to create an element that slides vertically, you have to prevent the page from sliding. Of course you only want to do this for the element you want to slide and not other areas of the page or the page won’t scroll properly.

This is how to do it using jQuery, you can do this in straight Javascript of course if you like.

The first thing we will need is an html page with some content and a block element we want to vertically slide. To demonstrate this I will create two columns. Column 1 will contain the element I want to slide, the other column will contain some paragraph tags filled with Lorem Ipsum to fill the page with enough content that it will scroll. And example page with all the code can be downloaded from Github.

I will be adding a class called .box to a div that is the block I will make vertically scrollable. Basically my first column will look like this:

<div class="c1">
    <div class="box"></div>

The first thing that I have to do is prevent the page from scrolling when I touch the box. To do this I bind an event to the box and prevent the default event from happening.

$('.box').bind('touchstart', function(event){
    // prevent the page from scrolling

The following code will move the box vertically as the finger touching it slides up and down. I have added a line of code to put the Y coordinates in the box for demonstration purposes.

// move the element vertically
$('.box').bind('touchmove', function(event){
    // get the y position of the first finger, must use originalEvent not the jQuery rewritten event
    y = event.originalEvent.touches[0].pageY;
    // this simply puts the y coordinate in the block for reference
    $('.box').text("y: " + y);

    // so the block doesn't scroll past the top of the page
        // position the block
        $('.box').css('top', y + 'px');

One gotcha to watch for, if you attempt to get the fingers Y coordinate straight from the event object, as one would expect, you will get an error. jQuery rewrites the event object, so to get in order to get the Y coordinate of the finger you need to pull it off of the “originalEvent” object instead.

Now with a little styling, a vertical slider can easily be built.