Git Product home page Git Product logo

swipe's Introduction

Swipe

Build Status npm version npm GitHub license

Swipe is the most accurate touch slider. It is extremely lightweight (only 6kb minified) and works across all browsers, including IE8+.

Support both React.js and Angular.js(v1)

Note

This repo is a continuation of the dead Swipe project. Our mission is to keep Swipe alive and moving forward, with maintenance fixes and new features. Pull Requests are welcome!

Usage

Preview

Preview Image

Thanks to @loup-brun

Installation

NPM

npm i swipejs

Yarn

yarn add swipejs

See the online example for a simple demo.

Import in your project

ES5

const Swipe = require('swipejs');

ES6 and newer

import Swipe from 'swipejs';

Markup

Swipe requires just a few lines of markup. Here is an example:

<div id="slider" class="swipe">
  <div class="swipe-wrap">
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>

Above is the initial required structure– a series of elements wrapped in two containers. Place any content you want within the items. The containing div will need to be passed to the Swipe function like so:

Style

Swipe requires the following styles to be added to your stylesheet:

.swipe {
  overflow: hidden;
  visibility: hidden;
  position: relative;
}
.swipe-wrap {
  overflow: hidden;
  position: relative;
}
.swipe-wrap > div {
  float: left;
  width: 100%;
  position: relative;
  overflow: hidden;
}

Javascript

You may initialize a Swipe slider with only one line of javascript code:

window.mySwipe = new Swipe(document.getElementById('slider'));

I always place this at the bottom of the page, externally, to verify the page is ready.

Options

Swipe can take an optional second parameter – an object of key/value settings:

Options Type Default Description
startSlide Integer 0 index position at which Swipe should start.
speed Integer 300 speed of prev and next transitions in milliseconds.
auto Integer 0 when specified, start an auto-playing slideshow (time in milliseconds between slide change).
continuous Boolean true create an infinite feel with no endpoints.
autoRestart Boolean false auto restart slideshow after user's touch event or next/prev calls.
disableScroll Boolean false prevent any touch events on this container from scrolling the page.
stopPropagation Boolean false stop event propagation.
draggable Boolean false listen to mouse events in addition to the touch events
ignore String null ignore touch events on any element matching this selector
callback Function null runs at slide change. Three parameters are passed to the function: index (the current slide index)elem (the current slide element) and dir (direction: 1 for left or backward-1 for right or forward).
transitionEnd Function null runs at the end of a slide transition. Two parameters are passed to the function: index (the current slide index) and elem (the current slide element).

Example

window.mySwipe = new Swipe(document.getElementById('slider'), {
  startSlide: 0,
  speed: 400,
  auto: 3000,
  draggable: false,
  continuous: true,
  disableScroll: false,
  stopPropagation: false,
  ignore: ".scroller",
  callback: function(index, elem, dir) {},
  transitionEnd: function(index, elem) {}
});

API

A Swipe instance exposes the following public methods:

Methods Description
prev() slide to the previous slide.
next() slide to the next slide.
getPos() return the current slide index position.
getNumSlides() return the number of slides.
slide(index, duration) slide to the position matching the index (integer) (duration: speed of transition in milliseconds).
restart() restart the slideshow with autoplay.
stop() stop the slideshow and disable autoplay.
setup(options) reinitialize swipe with options.
disable() disable slideshow.
enable() enable slideshow.
kill() completely remove the Swipe instance.

Supports

Browser Support

Swipe is now compatible with all browsers, including IE7+. Swipe works best on devices that support CSS transforms and touch events, but can be used without these as well. A few helper methods determine touch and CSS transition support and choose the proper animation methods accordingly.

React Support

Please go to react swipe plugin, or check the example

Angular(V1) Support

Please go to angular swipe plugin for source code and usage example.

Who's using Swipe

Send me a note if you want your logo here

License

The MIT License (MIT).

swipe's People

Contributors

aaronopfer avatar alicelieutier avatar baer avatar bdougherty avatar benmorel avatar benschwarz avatar cjbell avatar darep avatar dependabot[bot] avatar douwem avatar gerrit avatar i-like-robots avatar james2doyle avatar jamesjenner avatar jeroencoumans avatar jessy1092 avatar jonkoops avatar kmiklas avatar loup-brun avatar lyfeyaj avatar noorsilkaredia1 avatar pads avatar randscullard avatar rsusanto avatar solidfox avatar srikanth-wgl avatar stianlik avatar thebird avatar x-cray avatar yannklein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swipe's Issues

Probleme with auto restart prop

Hi.
i've a little probleme with swipe 2 and the autoRestart param.
If i dont set it to false and i and i click once on a "next" button , my swip gallery fall in a loop :
It didn't forward by just one step...

so i must write
autoRestart : false

thanks.

Add RTL Support

Hey, great work in the original project making this small and useful tool, exactly what I need!
Also great job maintaining and keeping this alive, thanks!

I'm working on an RTL website and after setting up Swipe I can't see anything.
Changing to <html dir="ltr"> make it work.
Also adding dir="ltr" to the Swipe container.
First is of course impossible, and the second is sub-optimal since the direction of sliding is the opposite.

I went over the code to see if it's an easy fix but it seems a couple of hours work (at least for me) to get all the calculations right.
Is there a plan to add a setting for direction?

problem when many childs

like:

<div id="slider" class="swipe">
  <div class="swipe-wrap">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    ...
    <div></div>
  </div>
</div>

the browser crashes especially in iOS.
I guess is that the memory overflowed.
Do you have any ways to deal with the problem ?

Feature request - Disable drag next/prev

I don't know if this is something you want to implements. But I have a use case where I would like to disable the user from dragging in the next or previous slide depending on the state in my application.

I have a slider that contains a start section with controls for joining a Quiz, the last section is to show the results of the Quiz. Between these sections are slides that represents each question. I would like to let the competitors of the quiz be able to drag the slider (on a mobile browser) between questions, but not to the first/last section. The swap to first/last section of the slider will be made through the code by triggering these states in a control panel kind of thing by another user in another app.

I hope to have explained my use case, but maybe this is a bit to advanced of a feature to be implemented in this elegant slider.

warning about reading key auto from empty options

The code from README.md return warning about reading key auto from empty options.

Javascript

You may initialize a Swipe slider with only one line of javascript code:

window.mySwipe = new Swipe(document.getElementById('slider'));

I always place this at the bottom of the page, externally, to verify the page is ready.

Cannot find module 'swipejs/react'

Hi!

Your package seems great, with typescript and react support.
However I can't manage to get it work...

I'm using webpack / react / typescript and when I'm trying to import Swipe and SwipeItem as described in your exemple, I'm having this error:
(10,34): error TS2307: Cannot find module 'swipejs/react'.

I'm currently using v2.2.3 of the package from npm.

Pagination

How to add numbering? For example, 3/7
Thank you!

onClick handler for React Swipe does not work when there's exactly 2 swipe items

Version 2.2.4

  1. Open the examples/react folder and replace app/app.jsx with the following code:
import React from 'react';
import ReactDom from 'react-dom';
import { Swipe, SwipeItem } from 'swipejs/react';

import 'swipejs/style.css';
import './style.css';

class ReactSwipeExampleApp extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(n) {
    console.log(`clicked ${n}`)
  }

  render() {
    return (
      <div className='react-swipe-example'>
        <h2>React Swipe Example</h2>
        <Swipe className='custom-swipe-container-class'
               ref='swipe'
               startSlide={0}
               speed={300}
               draggable={true}
               continuous={true}
               disableScroll={false}
               stopPropagation={false}>
          <SwipeItem className='custom-swipe-item-class'
                     onClick={() => this.handleClick(1)}>
            Slide One
          </SwipeItem>
          <SwipeItem className='custom-swipe-item-class'
                     onClick={() => this.handleClick(2)}>
            Slide Two
          </SwipeItem>
        </Swipe>
      </div>
    );
  }
}

ReactDom.render(<ReactSwipeExampleApp />, document.getElementById('react-swipe-example-app'));

  1. Run the example in the browser
  2. Click on the text when the example first loads. The click event should be logged in the console.
  3. Now, swipe left (i.e. click and move cursor to the right) by one screen and click the text again. The click event is not logged in the console.

Problems with 2 slides

      //special case if two slides
      if (browser.transitions && options.continuous && slides.length < 3) {
        element.appendChild(slides[0].cloneNode(true));
        element.appendChild(element.children[1].cloneNode(true));
        slides = element.children;
      }

These lines of code is creating a big problem, have anyone experienced any issues with them?
Because when im expecting to slide between 2 slides, i end up sliding between 4 and the index is Fed up. Reporting 0,1,2,3 as is reported here: thebird/Swipe#504

long time tap trigger

sorry this only happened in some android device...
@before update
with long time taped on the carousel, the swipe time may change to smaller than options.auto, and some times the sequence may not be right. tested on mobile browser. on tap without touch move.

slideTo function

Does it have an API yet? I need to use custom pagination (range slider) where I can jump the user between different pages quickly.

"to" has wrong type

The type of variable to in method slide() is of string. This results in wrong behavior if first slide is active and method slide() is called with last index (only if continuous is enabled).
In addition slider breaks whole page if slide() is called with current slide.

See pen: http://codepen.io/MichaB/full/PNMJYb/

The reason for this is, that to is of type string and not number.

pupulating dynamically does not work

var output = $('.swipe-wrap');
$.ajax({
        url: 'http://mywebsite.com/images/images_to_swiper.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){ 
                var landmark = '<div><img src="http://mywebsite.com//images/'+item.img+'" style="width:100%;"></img></div>';           
                output.append(landmark);

            }); 

        },
        error: function(){
            $( "#popupDialog" ).popup( "open" )
        }
    });

my php page returns a json encoded string like this:

([{"id":"19","img":"image1.png","posizione":"1"},{"id":"11","img":"anotherimage.jpg","posizione":"6"}]);

but slider is not populated. Any idea why?

some suggestions

Whenever the content of swipe > div contains other transitions it is posible that transitionEnd is triggered also. I had that when in my 'transitionEnd' handler I accidentally modified the height of an element. The transitionEnd kept firing.

I modified the swipe.js internal handler to:
if (event.propertyName == "transform" && parseInt(event.target.getAttribute('data-index'), 10) === index) {

Another thing is that I needed to know the swipes direction (to virtually add pages). So I added a 'direction' argument to the calling of the callback

offloadFn(options.callback && options.callback(getPos(), slides[index], direction));
and
options.callback(getPos(), slides[index], (direction ? -1 : 1));

Angularjs support

I've begun integrating Swipe into Angular.js. The integration works well so far and does not touch the original swipe.js file, but there are limitations in simply wrapping the library.

There are 3 main directives:

  • swipe-wrap: initializes the Swipe controller and thus will contain all the Swipe-related model/logic. Additional components (directives) may added within this wrapper, such as a counter or a controls directive;
  • swipe-slider: the actual slider;
  • swipe-item: a slide, which contains the client's html.

The swipe-wrap must be a parent of the swipe-slider, because the latter transcludes, thus creating a new, isolated scope that inherits from the $parent scope. Therefore, in order for the model to propagate correctly, the swipe-wrap must be parent of the slider.

All the Swipe options are supported. However, since the original swipe.js is untouched, I must create a new callback function which includes $scope.$apply() AND the client callback in order for every slide change to be added to the event loop. (otherwise, Angularjs doesn't know about the slide index when auto-playing the slider).

My suggestion is to port Swipe to a different core file designed for Angular.js. However, the integration I made works - just include angular.swipe.js before your custom app, given Swipe is already loaded as a global on the page.

Markup

<swipe-wrap>
  <swipe-slider data-options="Demo1.sliderConfig">
    <swipe-item>...</swipe-item>
    <swipe-item>...</swipe-item>
    <swipe-item>...</swipe-item>
  </swipe-slider>
  <!-- Other slide-related directives go here -->
</swipe-wrap>

<!-- Include the following scripts in the correct order before defining your app -->
<script src="angular.js"></script>
<script src="swipe.js"></script>
<script src="angular.swipe.js"></script>

Javascript

angular
  .module('myApp', ['swipe']) // require the swipe module
  .controller('DemoController', DemoController);

// Attach the app onto the document body
// Alternatively, use the directive form of the bootstrap function
angular.bootstrap(document.getElementsByTagName('body')[0], ['myApp']);

function DemoController() {
  var Demo = this;
  // Add an options object to your application controller
  Demo.sliderConfig = {
    startSlide: 0,
    speed: 400,
    auto: 3000,
    draggable: false,
    continuous: true,
    disableScroll: false,
    stopPropagation: false,
    callback: function(index, elem) {},
    transitionEnd: function(index, elem) {}
  };
}

width set to 0 for div 'swipe-wrap' and all the elements div in it

Hi,
I am using swipe in the auto-hiding menu, in the mobile version, the menu will only slide out when the menu button is clicked.
The swipe module works fine in the pc version, but does not work in the iPad or mobile version.
There are 2 issues I can currently observe

  1. div width set to 0 for both swipe-wrap and all its elements
  2. the js is not running through the divs. The js file suppose to change the attributes and make the slide 'run', but none of the <div> was changing.

Here is the html in pc version:

<div class="swipe" id="st-quotes" style="visibility: visible;">
<div class="swipe-wrap" style="width: 570px;">

<div data-index="0" style="width: 190px; left: 0px; transition-duration: 400ms; transform: translate(-190px, 0px) translateZ(0px);">slide1
</div>

<div data-index="1" style="width: 190px; left: -190px; transition-duration: 400ms; transform: translate(0px, 0px) translateZ(0px);">slide2
</div>
<div data-index="2" style="width: 190px; left: -380px; transition-duration: 0ms; transform: translate(190px, 0px) translateZ(0px);">slide3
</div>
</div>
</div>

And this is the html in mobile version:

<div class="swipe" id="st-quotes" style="visibility: visible;">
<div class="swipe-wrap" style="width: 0px;">

<div data-index="0" style="width: 0px; left: 0px; transition-duration: 0ms; transform: translate(0px, 0px) translateZ(0px);">slide1
</div>

<div data-index="1" style="width: 190px; left: 0px; transition-duration: 0ms; transform: translate(0px, 0px) translateZ(0px);">slide2
</div>
<div data-index="2" style="width: 190px; left: 0px; transition-duration: 0ms; transform: translate(0px, 0px) translateZ(0px);">slide3
</div>
</div>
</div>

Thanks for any help and tip in advance!

Feature request: Add a callback for a move

I have an indicator that should change its position depending on the current position of the slide that is being moved with the touch. When I start moving a slide, I want to change the indicator position and size depending on the current position of the slide that is being dragged.

So, It would be great to have a way to attach a callback to every 'move' event with some data inside, like coordinates, shift and other.

Thanks!

slider explodes on iOS and when viewport is resized

Hi, I'm having a number of issues with this slider - when i change the width or even height of the viewport, all the images can disappear.

When I load the slider on a page in iOS, the slider takes up the full height of all of the images combined, and the images are not visible. It appears to have exploded.

Is anyone else facing these brittle behaviour issues?

Can you suggest any other javascript carousel libraries for compatibility with IE11 and iOS?

how to fix the scroll between swipe and origin scroll

I use swipe like below:

<div id="slider" class="swipe">
  <div class="swipe-wrap">
    <div><div id='ex'></div></div>
    <div></div>
    <div></div>
  </div>
</div>

in style sheet.I set a 'overflow:auto' for ‘ex‘ and 'ex' width is larger than swipe.
here is the question:
it didn't work in swipe, seems like the overflow:auto 's scroll is conflict with scroll in swipe?
Is there any way to fix this in swipe or I just put this element outside?.I need this element to scroll and in different slide ,its' content is not same

TypeScript support

First, thanks for the great compact jQuery-less swipe library!

Can you please advise me if there is any d.ts file for this library or is there a chance you could include it into the repo or make it possible to fetch it from some identified source?

Calling setup onResize is unnecessary

The code is currently calling the setup method when the window resizes. The result is unnecessary processing and the addition of duplicative event handlers. Should probably just have a method which updates the positions and dimensions of the necessary elements.

 case 'resize': offloadFn(updateDimensions); break;

    function updateDimensions() {
      // determine width of each slide
      width = container.getBoundingClientRect().width || container.offsetWidth;

      element.style.width = (slides.length * width * 2) + 'px';

      // stack elements
      var pos = slides.length;
      while(pos--) {

        var slide = slides[pos];

        slide.style.width = width + 'px';
        slide.setAttribute('data-index', pos);

        if (browser.transitions) {
          slide.style.left = (pos * -width) + 'px';
          move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
        }

      }
    }

.kill() not executing properly on window resize [bug]

when using .kill() eg if i'm going from mobile view with swipe to desktop it dosent clean up all the inline styling

$(window).on('resize', function() {
    if($(window).width() < 800) {
        window.mySwipe = new Swipe(document.getElementById('slider'));
    } else {
        window.mySwipe.kill()
    }
});

Also if i only have to slides it doesn't clean up properly because of the "special case senario" on line 80 in swipe.js, there is no "special case senario" in the .kill() for that

Lazy loading

It would be really nice to support lazy loading of images.

Swipe only after first slide changes

It seems that the swipe gesture is disabled until the first slide has changed.

On the other hand, if I don't set an 'auto' value and swipe for the first time, then the slider starts scrolling continuosly.

offloadFn not used as intended

offloadFn is presumably used to delay execution of a function until the next execution cycle:
var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution

However, everywhere in the code where it is used, the argument function is called instead of sent as a reference:
offloadFn(options.callback && options.callback(getPos(), slides[index]));
case 'touchend': offloadFn(this.end(event)); break;

So these functions are not offloaded, and since they all lack return statements they evaluate to undefined and noop gets called from offloadFn.

This doesn't seem to have an impact on anything yet, but I thought you should be made aware. Let me know if I should submit a pull request with a fix!

full div images only displayed partially

I'm using swipe to display a continuous flow of images of width 640px. They were displayed truncated because measuring the width on line 90:
width = container.getBoundingClientRect().width || container.offsetWidth;
returned the width as being 40px less. I solved this by manually adding the width in the css like so:
.swipe {
width:640px;
...

Dynamic content

Hi there,

I am trying to use the plugin in a webapp but get stuck on how to handle dynamic content... I checked the original project and there are some suggestions but nothing buit-in, do you have a best practice to load new slides dynamically in the list ?

Thank you ;)

Wrong initial item width

The problem seems to be identical to this one.

I'm using the react component. Trying to run swipe.instance.setup() in componentDidMount does not work since it's undefined, only when the page completely renders is when setup() can be called and does what it's supposed to do. The width seems to be correct on mobile though.

Normalize Scroll Height

Is it possible for each slide to have it's own height? Right now the shorter slides have giant blank spaces below them since all the slides are the same height as the longest slide.

Related swipe.js issue: thebird/Swipe#116

width changes on touch scroll

I'm resizing the contained divs in my callback function, and the size/positioning of the divs seems to "jump/settle" only once I scroll over the div (on an iPhone), eg:

all2sides.com/mobile.html

I'm assuming this has something to do with the way I'm resizing the divs in the callback, but I'm not sure.

(relatedly, the widths seem screwed up when viewing this on a desktop, and this does not appear to change with scrolling).

Edge/Windows 10 Compatability

Seem Edge touch now uses some newer pointer events that are not working with swipe.

I have noticed that if I press and hold the touchscreen that a small box does appear and if I swipe, the screen will move slighly exposing the begining of the next IMG, but snaps back.

Any Sugestions?

Thanks,
Mike

id should be excluded when clone dom

i have dom structure like below.

<div id="slider" class="swipe">
  <div class="swipe-wrap">
    <div id="inner-1"></div>
    <div id="inner-2"></div>
  </div>
</div>

when i inspect Elements in devtools, i found that id has been cloned too

can't make it work... :(

I downloaded the zip file on my test web server, unzipped it and tried it locally. The page I see in my browser contains the introductory text but no slides (I see slides 0 and 1 that vanish after 3 seconds and the page is very long). What am I doing wrong?
I use chrome on linux 16.04 and apache 2 web server. It's not the browser because this snippet works perfectly https://codepen.io/justincavery/pen/saEyI/ . Nevertheless I can not make it work on my server.

mouse wheel

Great work!

Is there anyway to add mouse wheel support for Pinch\Zoom?

also

Would love simple < > overlays on the sides of the images like the bootstrap carousel has

Regards,
Mike

kill() should remove any throttled function timeouts

Currently if you call kill() on resize (e.g. to show the slider only at smaller sizes), the slider will be destroyed momentarily, before popping back into the page. This seems to be because kill() doesn't remove the throttled setup call from the window, so setup ends up getting called ~100ms after resizing/killing the slider.

ES6 Module Support

It would be wonderful to be able to use this as an ES6/ES2015 module!

Import Swipe from './swipe';

Height of the page

In my project, there are divs of different size. The problem is the height of the page will the height of biggest div.
Please add autoHeight feature
swipe.zip

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.