Monday, 3 March 2014

SwipeJS example

I needed a quick and simple touch page slider for a project and decided to use to the SwipeJS library. This library is compatible with all browsers from IE 7+ and supports the usual left/right touch swipes as well as an automatic slideshow feature.

The SwipeJS setup is straightforward. You need a two divs, one for each slide and one as a wrapper. Some minor CSS styling will be needed to display the slides inline. Finally, the Javascript swipe function needs to be called to start touch swipes. There are a number of additional parameters available to tweak the behaviour of the slider such as speed of transitions, auto slideshow and continuous slides.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>SwipeJS Example</title>
    
    <style>
    html,body{padding: 0; margin:0;}
        
    .swipe {
      overflow: hidden;
      visibility: hidden;
      position: relative;
    }
    .swipe-wrap {
      overflow: hidden;
      position: relative;
    }
    .swipe-wrap > div {
      float:left;
      width:100%;
      position: relative;
    }
    </style>
    
</head>
<body onload="init()">

    <div id='mySlider' class='swipe'>
      <div class='swipe-wrap'>
        <div><img src="images/pic1.jpg"/></div>
        <div><img src="images/pic2.jpg"/></div>
        <div><img src="images/pic3.jpg"/></div>
        <div><img src="images/pic4.jpg"/></div>
        <div><img src="images/pic5.jpg"/></div>
      </div>
    </div>

    <script src="swipe.js"></script>
    <script>
    
        function init(){
            var mySwipe = Swipe(document.getElementById('mySlider'), {
               speed:400,
               continuous: true,
            }); 
        }
        
    </script>
</body>
</html>

Currently, the slides are only swipe on mobile and tablet devices. To make this compatible with desktop, buttons will need to be added to navigate to the previous and next slides.

<span id="left" onclick="slideLeft()">left</span>
<span id="right" onclick="slideRight()">right</span>

<script>

    var mySwipe;

    function init(){  
        mySwipe = Swipe(document.getElementById('mySlider'),{
           speed:400,
           continuous: true,
        });   
    }

    function slideLeft(){
        mySwipe.prev();
    }

    function slideRight(){
         mySwipe.next();
    }

</script>

The jquery version uses the following code.

function init(){
    $(document).ready(function(){

        var slider = $('#mySlider').Swipe({
            speed:400,
            continuous: true,
        }).data('Swipe');

    });
}

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP