Menu
Is free
registration
home  /  Installation and configuration/ The simplest slider. Simple responsive jQuery touch slider

The simplest slider. Simple responsive jQuery touch slider

Simple, lightweight (21Kb compressed) slider written in pure Javascript, without any dependencies, i.e. works without jQuery.

Tested in the following browsers:

  • Chrome 26.0
  • Firefox 20.0
  • Safari 5.1.7
  • IE 10
  • Opera 16.0

There is incomplete support for IE8 / 9 (no effects).

Peculiarities

  • You can add an unlimited number of sliders to the page, even place one inside the other.
  • Resizes based on content, but can be disabled.
  • Keyboard Navigation - When the cursor is on the slider, you can toggle the arrow sliders.
  • Support for mobile touch events.

Connection

Before the closing tag need to connect slidr.js or slidr.min.js file.

HTML markup

slidr.js can work with any inline, inline-block, block elements that have an id attribute. It is allowed to use any first-level child elements with the data-slidr attribute, for example:

  • apple
  • banana
  • coconut
apple
banana
coconut

Javascript

After connecting slidr.js the global slidr object will become available. The easiest way to create a slidr is:

Slidr.create ("slidr-id"). Start ();

Call with all settings:

Slidr.create ("slidr-id", (after: function (e) (console.log ("in:" + e.in.slidr);), before: function (e) (console.log ("out: "+ e.out.slidr);), breadcrumbs: true, controls:" corner ", direction:" vertical ", fade: false, keyboard: true, overflow: true, theme:" # 222 ", timing: (" cube ":" 0.5s ease-in "), touch: true, transition:" cube ")). start ();

Settings

All available settings for slidr.js are shown in the table below.

Parameter Type of Default Description
after function callback function after slide change
before function callback function before slide change
breadcrumbs bool false Show breadcrumbs for slide control. true or false.
controls string border Arrangement of arrows to control slides. border, corner or none.
direction string horizontal The default direction for new slides. horizontal or h, vertical or v.
fade bool true Enable fade-in / out effect. true or false.
keyboard bool false Enable changing of slides using the keyboard. true or false.
overflow bool false Enable overflow for the slider block. true or false.
pause bool false Don't change slides automatically on mouse hover (you need to run auto ()). true or false.
theme string #fff The color of the slider controls (breadcrumbs and arrows). #hexcode or rgba (value).
timing object {} Custom animation timings to apply. ("transition": "timing").
touch bool false Enable touch control on mobile devices. true or false.
transition string linear Slide transition effect. cube, linear, fade, or none.

The after and before callback functions receive the following data:

(id: "slidr-id", in: (el: # , slidr: "data-slidr-in", trans: "transition-in", dir: "direction-in"), out: (el: # , slidr: "data-slidr-out", trans: "transition-out", dir: "direction-out"))

Slider.js global API

The slidr global namespace provides the following functionality:

/ ** * Current version * @return (string) major.minor.patch. * / function version () (); / ** * Available transition effects. * @return (Array) of transitions. * / function transitions () (); / ** * Creates and returns Slidr. * Calling this function twice on the same element will return the already created Slidr object. * @param (string) element id for Slidr. * @param (Object =) opt_settings Slider settings. * / function create (id, opt_settings) ();

Slider API

// Initialize Slidr with custom settings var s = slidr.create ("slidr-api-demo", (breadcrumbs: true, overflow: true)); // Add horizontal slides with a standard transition effect. // duplicate array element "one" at the end lets Slidr // scroll the slides endlessly s.add ("h", ["one", "two", "three", "one"]); // Adds a vertical slide with a cube transition effect. s.add ("v", ["five", "four", "three", "five"], "cube"); // Launch the slider. s.start ();

Short entry

Var s = slidr.create ("slidr-api-demo", (breadcrumbs: true, overflow: true)). Add ("h", ["one", "two", "three", "one"]) .add ("v", ["five", "four", "three", "five"], "cube") .start ();

The complete list of Slidr.js API functions is presented below.

/ ** * Start the Slidr! * Automatically finds slides to create if nothing was added prior to calling start (). * @param (string) opt_start `data-slidr` id to start on. * @return (this) * / function start (opt_start) (); / ** * Check whether we can slide. * @param (string) next a direction ("up", "down", "left", "right") or a `data-slidr` id. * @return (boolean) * / function canSlide (next) (); / ** * Slide! * @param (string) next a direction ("up", "down", "left", "right") or a `data-slidr` id. * @return (this) * / function slide (next) (); / ** * Adds a set of slides. * @param (string) direction `horizontal || h` or `vertical || v`. * @param (Array) ids A list of `data-slidr` id" s to add to Slidr. Slides must be direct children of the Slidr. * @param (string =) opt_transition The transition to apply between the slides, or uses the default. * @param (boolean =) opt_overwrite Whether to overwrite existing slide mappings / transitions if conflicts occur. * @return (this) * / function add (direction, ids, opt_transition, opt_overwrite) (); / ** * Automatically advance to the next slide after a certain timeout. Calls start () if not already called. * @param (int =) opt_msec The number of millis between each slide transition. Defaults to 5000 (5 seconds). * @param (string = ) opt_direction "up", "down", "left", or "right". Defaults to "right". * @param (string =) opt_start The `data-slidr` id to start at (only works if auto is called to start the Slidr). * @return (this) * / function auto (opt_msec, opt_direction, opt_start) (); / ** * Stop auto transition if it "s turned on. * @return (this) * / function stop () (); / ** * Set custom animation timings. * @param (string | Object) transition Either a transition name (i.e. "cube"), or a ("transition": "timing") object. * @param (string =) opt_timing The new animation timing (i.e "0.5s ease-in"). Not required if transition is an object. * @return (this) * / function timing (transition, opt_timing) (); / ** * Toggle breadcrumbs. * @return (this) * / function breadcrumbs () (); / ** * Toggle controls. * @param (string =) opt_scheme Toggle on / off if not present, else change layout. "border", `corner` or` none`. * @return (this) * / function controls (opt_scheme) ();

Scrolling the page while changing slides

This nasty bug appears in some browsers. To fix it, you need to add style to the body:

Body (overflow: hidden;)

Dynamic resizing

Slidr "understands" whether the slider needs to be resized to fit the image. If the slider block has dimensions specified, then Slidr will not automatically change them. If the min-width and min-height properties are specified, then the slider will resize to fit the content, taking these values ​​into account. Otherwise, sizing will be performed automatically.

Automatic resizing

good
gorgeous
unbelievable

Static dimensions

good
gorgeous
unbelievable

Slidr controls

The markup for the controls is as follows:

You can customize any slider control using CSS selectors:

Aside .slidr-control.right (width: 50px! Important; height: 50px! Important; top: 50%! Important; margin-top: -25px! Important; right: -25px! Important; border-radius: 25px; background : url ("/ static / images / arrow_right.png") 14px 13px no-repeat black; opacity: 0.4;) aside .slidr-control.right: hover (opacity: 1;)

The arrow control is implemented with the: after pseudo selector, so to hide it, use the following code:

// Hide a single arrow within a single controller. aside .slidr-control.right: after (border-color: transparent! important;) // Hide all arrows within a single controller. aside .slidr-control: after (border-color: transparent! important;) // Hide all Slidr arrows. aside .slidr-control: after (border-color: transparent! important;)

Slidr Breadcrumbs

Breadcrumbs have simple HTML markup. Each ul stands for an entire line, and each li stands for a separate breadcrumb:

Styling breadcrumbs with CSS:

// Customize the position, size, border color and background color. aside (right: 50%! important; margin-right: -41px! important;) aside .slidr-breadcrumbs li (width: 15px! important; height: 15px! important; margin: 3px! important;) aside .slidr-breadcrumbs li.normal (border-color: white! important;) aside .slidr-breadcrumbs li.active (background-color: black! important;)

License

This software is free to use under the MIT license.

From the author: Despite rumors about the alleged "death" of the part of web pages visible without scrolling, the need for a good slider has not disappeared anywhere. Let's be honest, just for a second - sliders are fun. In addition, nothing else, unlike moving content, causes a wow effect for the user. All sliders are a set of several slides that replace each other and it is extremely important that the slider code is as light as possible. This is where jQuery comes in handy.

Take a look at the 20 jQuery sliders from Envato Market and you'll see that there are sliders that are more than just a block of smoothly changing images.

1. RoyalSlider - Touchscreen image gallery on jQuery

A responsive slider that is also touch-friendly means a lot more now than it used to. RoyalSlider combines both responsiveness and touchscreen functionality. Good choice as the gallery is written in HTML5 and CSS3.

Several interesting features:

JavaScript. Fast start

SEO optimization

High customization

Over 10 starter templates

There is a fallback for CSS3 transitions

In my opinion, the coolest feature is the "modular script architecture", which allows you to exclude unnecessary things from the main JS file, thereby reducing weight. RoyalSlider, a jQuery image touchscreen gallery, is a robust JavaScript slider that should be a must-have for any developer's toolbox.

2. Slider Revolution responsive jQuery plugin

It's not easy to do something "revolutionary" with a slider. There are so many functions you can add when it comes to sliders. However, Slider Revolution is a really good try. Among the jQuery sliders, this instance meets all your possible requirements.

The list of slider features is so long, so I will list only the best ones:

Parallax effect and custom animation

Unlimited layers and slides with links

ready to use, deeply customizable styles

and much more

The ability to add an image, built-in video player and social media links makes Slider Revolution one of the most flexible and customizable options on the web.

3. LayerSlider responsive jQuery slider plugin

The name "LayerSlider responsive jQuery plugin slider" cannot really appreciate this slider.
200+ 2D and 3D slide transitions will make anyone's head spin.

A couple of notable features:

13 skins and 3 types of menus

Ability to place a fixed image on top of the slider

And jQuery fallback

And much more

As with the previous slider, you can add almost any content, even HTML5 resident multimedia content. LayerSlider brings sliders to life and is very pretty.

4.jQuery Banner Rotator / Slideshow

jQuery Banner Rotator / Slideshow is a fairly simple slider that doesn't sacrifice core functionality.

Possibilities:

Tooltips, text inserts, etc.

Preview and various options for viewing components

Timer with delay for one slider or for all

Multiple transitions for all slides or different transitions for each separately

jQuery Banner Rotator / Slideshow has only basic features compared to other jQuery sliders, but you shouldn't forget about it.

5. All In One Slider - Responsive jQuery slider plugin

Any slider that appears on the web has its own unique vision and solves any problems in its area. But not this one. All In One Slider can be called all inclusive.

I think most web developers and designers have a proven solution, but they are always looking for something new. And this "something new" includes:

Banner rotator

Banner with preview

Playlist banner

Content slider

Carousel

All slider types support most, if not all, of the functionality that jQuery sliders need. Will All In One Slider be your all inclusive?

6. UnoSlider - Adaptive touchscreen slider

If your slider is not responsive and does not support touch screens, then you have the wrong slider. UnoSlider is correct.

This slider has found its place in the sun between simplicity and rich feature set. Functions:

Support for themes

12 ready-made themes

40 transitions

IE6 + support

All features with a bias in design and style, which makes UnoSlider an excellent content slider with the ability to add themes.

7.Master Slider - jQuery touchscreen slider

Looking for “one jQuery slider to rule them all”? Try Master Slider - jQuery touchscreen slider for different screen sizes ...

When it comes to good design, this one is one of the best:

More than 25 templates

Hardware accelerated transitions

Support for touches and swipes

And much more

Interactive transitions, animated layers and hotspots will definitely grab your attention. Master Slider is a work of art.

8. TouchCarousel - jQuery content scroller and slider

TouchCarousel attracts with free support and updates. However, these are not all the features of this lightweight jQuery carousel slider.

If the name contains the word "touch", you can guess that the slider is fully responsive and supports touching. Other functions:

SEO optimization

Smart autoplay

Hardware accelerated CSS3 transitions

Customizable UI and 4 Photoshop skins

TouchCarousel offers a whole new level of experience on mobile due to its unique physical slide scrolling.

9.Advanced Slider - jQuery XML slider

jQuery sliders aren't just for websites. They can also come in handy in web applications. Advanced Slider allows you to do this.

With HTML or XML markup, this advanced slider makes a lasting impression:

Animated layers and smart video

100+ transitions and 150+ custom properties

15 slider skins, 7 scrollbar skins and built-in lightbox support

Keyboard navigation, touch support and full customization

And much more

However, the best feature is Advanced Slider - the jQuery XML Slider API, which makes the slider ideal for your web application.

10.jQuery Slider Zoom In / Out Effect Fully Responsive

One of those jQuery sliders that will make you watch a demo before you start reading about its capabilities. You just want to understand what this "zoom in / out effect" means.

The zoom effect is quite weak, but it adds a sense of control and real touch to the image while the rest of the slider is static. Special features of the slider:

CSS3 transitions between layers

Animation end option for layers

Fixed-width, full-screen and full-width options

Animated text with HTML and CSS formatting

Most sliders try to incorporate as many effects as possible, and jQuery Slider Zoom In / Out Effect Fully Responsive has only the Ken Burns effect, but it is well implemented.

11.jQuery Carousel Evolution

Like the aforementioned Advanced Slider - jQuery XML Slider, jQuery Carousel Evolution has its own API that can be used to enhance the functionality or integrate the slider into another project.

JavaScript. Fast start

Learn the basics of JavaScript with a hands-on example of building a web application

With images, HTML markup, YouTube and Vimeo videos, you also get:

SEO optimization

9 carousel styles

Shadow and reflection effects

Image size can be adjusted, both front and back

jQuery Carousel Evolution is a simple carousel with many use cases.

12. Sexy Slider

Sexy Slider is no longer as sexy as it used to be. However, due to its age, this slider is trustworthy.

At first glance, the slider is not very impressive, but if set up well, it will fit perfectly into your design. Possibilities:

Autoplay slides

Image captions

Continuous playback of slides

6 transition effects

Sexy Slider is waiting for you to unleash its full power and potential.

13.jQuery Image & Content Scroller w / Lightbox

With all these mobile designs and touchscreen support, it's nice to see a jQuery slider that hasn't forgotten the desktop experience.

jQuery Image & Content Scroller w / Lightbox supports keyboard and mouse wheel input and other features:

Horizontal and vertical orientation

Text captions inside or outside the slider

Ability to set a specific number of slides visible at a time

Inline images, Flash, iframes, Ajax and inline content

The slider also has a built-in lightbox. If desired, in jQuery Image & Content Scroller w / Lightbox, you can not launch the slider itself, but separately launch the lightbox.

14. Translucent - Responsive banner rotator / slider

Most jQuery sliders have their own designs. You can customize it for yourself, but sometimes you just want everything to be inside the slider. We present to your attention Translucent.

There are a lot of presets in the slider. Perhaps you just need to configure certain settings and that's it. Possibilities:

6 different styles

4 transition effects

2 swipe transitions

Customizable buttons and captions

Like others, this slider is touch sensitive, responsive and hardware accelerated. Translucent is a slider with a minimal design that puts the content itself at the forefront.

15. FSS - Full Screen Sliding Website Plugin

Do you want to make a full screen slide site? Then you need FSS.

In fact, it is extremely easy to create a full screen slider site with this jQuery slider. Possibilities:

AJAX support

Scrollbar

Deep linking technology support

2 different transition effects

Also worth looking at is keyboard support and an 11-page guide. However, the real impression is caused by the weight of the FSS, only 5Kb.

16. Zozo Accordion - Adaptive touchscreen slider

Another example of a style-focused jQuery slider that does a pretty good job. The Zozo Accordion is a must for anyone looking for a good slider accordion with the ability to change styles.

This beauty with CSS3 animation also has a fairly wide range of features:

Horizontal and vertical accordion

Semantic HTML5 and SEO Optimization

Touch, keyboard and WAI-ARIA support

More than 10 skins and 6 layouts

And much more

Zozo Accordion has free support and constant updates, and all the features you want to see in a jQuery accordion.

17.jQuery Responsive OneByOne Slider Plugin

jQuery Responsive OneByOne Slider Plugin is more like a simple animation rather than a slider. Instead of displaying one slide at a time, this instance fills the screen with slides step by step until there is no room in the area before moving on to the next slide.

CSS3 animations work from within Animate.css, they are lightweight, multi-layered and mobile friendly. Several functions:

There is also a drag and drop navigation option. jQuery Responsive OneByOne Slider Plugin is powered by Twitter Bootstrap carousel.

18. Accordionza - jQuery plugin

No jQuery slider is easier than this. It only needs a 3KB slider to work, making the Accordionza the lightest accordion slider ever.

If you don't like the three styles, you can tweak the HTML and CSS yourself. Possibilities:

Keyboard navigation

Easy to customize effects and buttons

Progressive enhancement technique - works without JavaScript

Remember that Accordionza can display many variations of mixed content, making it extremely flexible.

19.mightySlider - Responsive multipurpose slider

MightySlider is a really powerful slider. It can be used not only as a simple image slider, but also as a full screen unidirectional slider with navigation through menu items. It can be used to make a great one-page website.

You will find many options under the hood:

Keyboard, mouse and touch support

Hardware accelerated CSS3 transitions

Clean Valid Markup and SEO Optimization

Unlimited number of slides, layers for captions and effects for them

The API is very powerful and developer friendly, which opens up different ways to use it. MightySlider is an excellent, progressive jQuery slider with clean and well commented code.

20. Parallax Slider - Responsive jQuery plugin

Parallax Slider works like the jQuery Responsive OneByOne Slider Plugin and lets you animate each layer separately within a single slide. You can animate all slides or even just one by adding parallax animation.

The set includes 4 sliders of different types, all with parallax effect. Like other jQuery sliders, it has:

Fully customizable

Touch support

Fully responsive, unlimited layers

Autoplay, Loop, Height and Width Adjustment, and Timer

Animated layers aren't just about text or images. You can also add YouTube, Vimeo and HTML5 videos. Parallax Slider is another good example of how you can simulate Flash effects even better than Flash itself, which is also supported on all devices.

Conclusion

It's interesting to see how jQuery sliders have grown from something that simply swaps one image for another, into a huge set of creative tools. Now there are 3D, parallax sliders, full page sliders, adaptive ones and those that can be viewed on both desktop computers and smartphones.

If you don't like any of the slides on this list, you can always follow the jQuery Code Tutorial on Envato and develop something completely new and unique.

Or check out the other sliders on Envato Market for a variety of options. What's your favorite jQuery slider and why?

We need a simple slider with automatic scrolling. Let's get started ...

Description of the slider's work.

The slides will be lined up and scrolled after a certain amount of time.

The red frame shows the visible part of the slider.

At the end of the slider, you need to duplicate the first slide. This is necessary in order to ensure scrolling from the third slide to the first. You also need to add the last slide to the beginning to be able to scroll backwards from the first slide to the third. Shown below is how the slider works in the forward direction.

When the slider reaches the end, a copy from the beginning of the slider is instantly placed in place of the last slide. Then the cycle repeats again. This creates the illusion of an endless slider.

HTML markup

First, let's make a simple auto-scrolling slider. It needs two containers to work. The first will set the size of the visible area of ​​the slider, and the second is needed to place the sliders in it. The slider markup will look like this:

> >

Slider styles

.slider-box (width: 320px; height: 210px; overflow: hidden;) .slider (position: relative; width: 10000px; height: 210px;) .slider img (float: left; z-index: 0;)

The.slider-box container sets the dimensions of the slider. The overflow: hidden property hides all elements that do not fall within the area inside the element.

The slider container is set to a large width. This is necessary so that all the slides fit into it.

Slides are aligned using the float: left property.

Below is a schematic layout of the slider blocks.

Script

The movement of the slides will be done by smoothly changing the container's slider margin-left property.

$ (function () (var width = $ (". slider-box") .width (); // Slider width. interval = 4000; // Interval for changing slides.$ (". slider img: last") .clone () .prependTo (".slider"); // A copy of the last slide is placed at the beginning.$ () .eq (1) .clone () .appendTo (".slider"); // A copy of the first slide is placed at the end. // The container.slider is shifted to the left one slide width. setInterval ("animation ()", interval); // The animation () function is run to change slides.)); function animation () (var margin = parseInt ($ (". slider") .css ("marginLeft")); // Current offset of the block. Slider width = $ (". slider-box") .width (), // Slider width. slidersAmount = $ (". slider") .children () .length; // The number of slides in the slider. if (margin! = (- width * (slidersAmount- 1))) // If the current slide is not the last one,(margin = margin- width; // then the margin value is reduced by the width of the slide.) else ( // If the last slide is shown,$ (". slider") .css ("margin-left", - width); // then the slider block returns to its starting position, margin = - width * 2; ) $ (". slider") .animate ((marginLeft: margin), 1000); // The slider block is shifted to the left by 1 slide. } ;

The result is a simple slider with infinite automatic scrolling.

To begin with, this article was written with the goal of telling you how to create an image scrolling slider for web pages. This article is by no means educational in nature, it only serves as an example of how you can implement our object of consideration. You can use the code provided in this article as a kind of template for such developments, I hope that I will be able to convey the whole essence of what I have written to the reader in sufficient detail and in an accessible way.



And now to the point, not so long ago I needed to put a slider on one site, but after searching the Internet for ready-made scripts, I did not find anything worthwhile. some did not work as I needed, while others did not start at all without errors in the console. Use jQuery - plugins it seemed to me too uninteresting for the slider, tk. Although I will solve the problem with this, I will not have an understanding about the operation of this mechanism, and using the plugin for the sake of one slider is not very optimal. I also didn't really want to understand crooked scripts, so I decided to write my own script for the slider, which I myself will mark up as I need.


To begin with, we need to decide on the logic of the slider itself, and then proceed to the implementation, at this stage it is very important to have a clear understanding of the operation of this mechanism, because without it we cannot write code that works exactly as we want.


Our main object will be viewport, that is, a block in which we will see how our pictures are spinning, in it we will have slidewrapper, this will be our block containing all the images, lined up in one line, and which will change its position inside the very viewport.


Further, on the sides inside viewport, vertically in the middle, the back and forward buttons will be located, upon clicking on which we will also change the position of our slidewrapper relatively viewport, thereby causing the effect of scrolling through pictures. And finally, the last object will be our navigation buttons located at the bottom. viewport.


When clicking on them, we will simply look at the serial number of this button and move to the slide we need, again by shifting slidewrapper(the offset will be done through the change transform css properties, the value of which will be constantly calculated).


I think the logic of this whole case should be clear after what I have stated above, but if there are still misunderstandings somewhere, then everything will be cleared up in the code below, you just need a little patience.


Now let's write! First of all, we will open our index file and write the markup we need there:



As you can see, nothing complicated block-for-slider serves as just the same block in which our slider will be placed, inside it itself viewport in which our slidewrapper, aka nested list, here li are slides and img- pictures inside them. Please pay attention to the fact that all pictures must be of the same size or, at least, proportions, otherwise the slider will look crooked, tk. its dimensions directly depend on the aspect ratio of the image.


Now we need to stylize this whole thing, usually the styles are not really commented on, but I decided to draw attention to this, so that there would be no misunderstanding in the future.


body (margin: 0; padding: 0;) # block-for-slider (width: 800px; margin: 0 auto; margin-top: 100px;) #viewport (width: 100%; display: table; position: relative; overflow: hidden; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;) #slidewrapper ( position: relative; width: calc (100% * 4); top: 0; left: 0; margin: 0; padding: 0; -webkit-transition: 1s; -o-transition: 1s; transition: 1s; -webkit -transition-timing-function: ease-in-out; -o-transition-timing-function: ease-in-out; transition-timing-function: ease-in-out;) #slidewrapper ul, #slidewrapper li (margin : 0; padding: 0;) #slidewrapper li (width: calc (100% / 4); list-style: none; display: inline; float: left;) .slide-img (width: 100%;)

Let's start with block-for-slider, this, again, is our block on the page, which we will set aside for the slider, its height will depend on its width and on the proportions of our image, since viewport takes up the entire width block-for-slider then myself slide has the same width, and, accordingly, the picture inside it changes its height depending on the width (the proportions are preserved). I placed this element horizontally in the middle on my page, padding 100px from the top, making its position more convenient for an example.


Element viewport, as already mentioned, occupies the entire width of our block-for-slider, it has the property overflow: hidden, it will allow us to hide our image feed, which will pop out of the viewport.


Following css property - user-select: none, allows you to get rid of the blue selection of individual slider elements with multiple clicks on the buttons.


Moving on to slidewrapper why position: relative, but not absolute? Everything is very simple, tk. if we choose the second option, then with the property viewport overflow: hidden absolutely nothing will seem to us, tk. myself viewport will not adjust to the height slidewrapper, because of what will have height: 0... Why does width matter so much, and why are we setting it at all? The fact is that our slides will have a width equal to 100% of viewport, and in order to arrange them in a line, we need a place where they will stand, thus the width slidewrapper should equal 100% viewport width multiplied by the number of slides (in my case, 4). Concerning transition and transition-timing-function then here 1s means that a change in position slidewrapper will occur within 1 second and we will observe it, and ease-in-out- the kind of animation in which it first goes slowly, accelerates to the middle, and then slows down again, here you can already set the values ​​at your discretion.


The next block of properties sets slidewrapper and its children have zero padding, comments are unnecessary here.


Next, we will style our slides, their width should be equal to the width. viewport, but since they are in slidewrapper, the width of which is equal to the width of the viewport multiplied by the number of slides, then to get the width viewport again, we need 100% of the width slidewrapper divide by the number of slides (in my case, again, by 4). Then we turn them into inline elements using display: inline and set the flow to the left by adding the property float: left... About list-style: none I can say that I use it to remove the default marker from li, in most cases is a kind of standard.


With slide-img everything is simple, the picture will take up the entire width slide, slide adjusts to its height, slidewrapper adjusts to the height slide, and the height viewport in turn will take the value of the height slidewrapper, thus the height of our slider will depend on the aspect ratio of the image and the size of the block provided for the slider, which I already wrote about above.


I think this is where we figured out the styles, let's make a simple slide show without buttons for now, and after making sure that it works properly, add and style them.


Let's open our js file, which will contain the slider code, do not forget to include jQuery since we will write using this framework. By the way, at the time of this writing, I am using the version jQuery 3.1.0... The file with the script itself must be included at the very end of the tag body since we will be working with the DOM elements that need to be initialized first.


For now, we need to declare a couple of variables, one will store the slide number that we see at a certain point in time in viewport, I named her slideNow, and the second will store the number of these same slides, this is slideCount.


var slideNow = 1; var slideCount = $ ("# slidewrapper"). children (). length);

Variable slideNow it is necessary to set the initial value 1, because when the page loads, we, based on our markup, will see the first slide in viewport.


V slideCount we will put the number of children slidewrapper, everything is logical here.
Next, you need to create a function that will be responsible for switching slides from right to left, we will declare it:


function nextSlide () ()

We will call it in the main block of our code, which we will get to, but for now we will tell our function what it needs to do:


function nextSlide () (if (slideNow == slideCount || slideNow<= 0 || slideNow >slideCount) ($ ("# slidewrapper"). css ("transform", "translate (0, 0)"); slideNow = 1;) else (translateWidth = - $ ("# viewport"). width () * ( slideNow); $ ("# slidewrapper"). css (("transform": "translate (" + translateWidth + "px, 0)", "-webkit-transform": "translate (" + translateWidth + "px, 0 ) "," -ms-transform ":" translate ("+ translateWidth +" px, 0) ",)); slideNow ++;))

First, we check if we are now on the last slide of our feed? To do this, we take the number of all our slides using $ ("# slidewrapper"). children (). length and check it with the number of our slide, if they turn out to be equal, then this means that we need to start showing the ribbon again, from 1 slide, which means we change css transform property at slidewrapper on translate (0, 0), thus shifting it to its original position so that the first slide appears in our field of view, do not forget also about –Webkit and –ms for adequate cross-browser display (see. css properties reference). After that, let's not forget to update the value of the variable. slideNow, informing her that slide number 1 is in her field of view: slideNow = 1;


The same condition includes checking that the number of the slide that we see is within the limits of the number of our slides, if somehow this is not fulfilled, then we will return to the 1st slide.


If the first condition is not met, then this means that at the moment we are not on the last slide, or on some nonexistent one, which means we need to switch to the next one, we will do it by shifting slidewrapper to the left by a value equal to the width viewport, the displacement will again occur through the familiar property translate whose value will be equal to "translate (" + translateWidth + "px, 0)", where translateWidth- the distance by which our slidewrapper... By the way, let's declare this variable at the beginning of our code:


var translateWidth = 0;

After moving to the next slide, tell our slideNow that we see the next slide: slideNow ++;


At the moment, some readers may have a question: why did not we replace $ ("# viewport"). width () to some variable, for example slideWidth to always have the width of our slide at hand? The answer is very simple, if our site is responsive, then, accordingly, the block allocated for the slider is also adaptive, from this it can be understood that when changing the size of the window width without reloading the page (for example, turning the phone sideways), the width viewport will change, and, accordingly, the width of one slide will also change. In this case, our slidewrapper will be shifted by the value of the width that was originally, which means that the pictures will be displayed in parts or not at all displayed in viewport... By writing to our function $ ("# viewport"). width () instead of slideWidth we make it calculate the width every time we switch slides viewport, thereby providing a scroll to the desired slide when the screen width changes abruptly.


However, we wrote the function, now we need to call it after a certain time interval, we can also store the interval in a variable, so that if we want to change it, change only one value in the code:


var slideInterval = 2000;

Time in js is specified in milliseconds.


Now let's write the following construction:


$ (document) .ready (function () (setInterval (nextSlide, slideInterval);));

Everything is nowhere easier, we are through the construction $ (document) .ready (function () ()) we say that the following actions must be performed after the document is fully loaded. Then we just call the function nextSlide with an interval equal to slideInterval, using the built-in function setInterval.


After all the actions that we performed above, our slider should spin fine, but if something went wrong with you, then the problem may be either in the version jQuery, or in the wrong connection of any files. Also, it is not necessary to exclude that you could have made a mistake somewhere in the code, so I can only advise you to double-check everything.


In the meantime, move on, add to our slider such a function as stop scrolling on hover, for this we need to write in the main block of code (inside $ (document) .ready (function () ())) such a thing:


$ ("# viewport"). hover (function () (clearInterval (switchInterval);), function () (switchInterval = setInterval (nextSlide, slideInterval);));

To start analyzing this code, we need to know what is switchInterval... Firstly, this is a variable that stores a periodic call to the nextSlide function, to put it simply, we use this line of code: setInterval (nextSlide, slideInterval);, turned into this: switchInterval = setInterval (nextSlide, slideInterval);... After these manipulations, our main block of code took the following form:


$ (document) .ready (function () (var switchInterval = setInterval (nextSlide, slideInterval); $ ("# viewport"). hover (function () (clearInterval (switchInterval);), function () (switchInterval = setInterval ( nextSlide, slideInterval);));));

Here I am using event hover, which means "on hover", this event allows me to track the moment when I hover over an object, in this case on viewport.


After hovering, I clear the spacing, which I will indicate in parentheses (this is our switchInterval), then, separated by commas, I write what I will do when I move the cursor back, in this block I again assign to our switchInterval periodic function call nextSlide.


Now, if we check, we will see how our slider reacts to mouse hover, stopping the slide switching.


Now it's time to add buttons to our slider, let's start with the back and forth buttons.


First of all, let's mark them up:



At first, this markup may be incomprehensible, I will say right away that I wrapped these two buttons into one div with class prev-next-btns just for your convenience, you do not have to do this, the result will not change, now we will add styles to them and everything will become clear:


# prev-btn, # next-btn (position: absolute; width: 50px; height: 50px; background-color: #fff; border-radius: 50%; top: calc (50% - 25px);) # prev- btn: hover, # next-btn: hover (cursor: pointer;) # prev-btn (left: 20px;) # next-btn (right: 20px;)

First, we position our buttons via position: absolute, thereby we will freely control their position within our viewport, then we will indicate the sizes of these buttons and using border-radius round the corners so that these buttons turn into circles. Their color will be white, that is #fff, and their indent from the top edge viewport will be equal to half the height of this viewport minus half the height of the button itself (in my case 25px) so we can position them vertically in the center. Next, we will indicate that when we hover over them, our cursor will change to pointer and finally tell our buttons individually to indent 20px from their edges so that we can see them as we see fit.


Again, you can style the page elements however you want, I am just giving an example of the styles that I decided to use.


After styling, our slider should look something like this:


Next, go back to our js file where we describe how our buttons work. Well, let's add another function, it will show us the previous slide:


function prevSlide () (if (slideNow == 1 || slideNow<= 0 || slideNow >slideCount) (translateWidth = - $ ("# viewport"). width () * (slideCount - 1); $ ("# slidewrapper"). css (("transform": "translate (" + translateWidth + "px, 0 ) "," -webkit-transform ":" translate ("+ translateWidth +" px, 0) "," -ms-transform ":" translate ("+ translateWidth +" px, 0) ",)); slideNow = slideCount;) else (translateWidth = - $ ("# viewport"). width () * (slideNow - 2); $ ("# slidewrapper"). css (("transform": "translate (" + translateWidth + "px , 0) "," -webkit-transform ":" translate ("+ translateWidth +" px, 0) "," -ms-transform ":" translate ("+ translateWidth +" px, 0) ",)); slideNow--;))

It is called prevSlide, it will be called only when you click on prev-btn... First, we check to see if we are on the 1st slide or not, here we also check if our slideNow beyond the boundaries of the real range of our slides and, if any of the conditions works, we will move to the last slide by shifting slidewrapper to the value we need. We will calculate this value by the formula: (width of one slide) * (number of slides - 1), we take all this with a minus sign, since we shift it to the left, it turns out that viewport will now show us the last slide. At the end of this block, we also need to tell the variable slideNow that the last slide is now in our field of vision.


If we are not on the first slide, then we need to move 1 backward, for this we again change the property transform for slidewrapper... The formula is as follows: (width of one slide) * (number of the current slide - 2), again, we take all this with a minus sign. But why is -2, and not -1, do we need to move just 1 slide back? The fact is that if we are, say, on the 2nd slide, then the variable x properties transform: translate (x, 0) our slidewrapper is already equal to the width of one slide, if we tell him that we need to subtract 1 from the number of the current slide, then we will again get the unit by which it is already shifted slidewrapper, so you will need to shift these very widths by 0 viewport, which means on slideNow - 2.



Now we just need to add these lines to the main block of code:


$ ("# next-btn"). click (function () (nextSlide ();)); $ ("# prev-btn"). click (function () (prevSlide ();));

Here we just track whether a click was made on our buttons, and in this case we call the functions we need, everything is simple and logical.


Now let's add the slide navigation buttons, back to the markup:



As you can see, inside viewport a nested list appeared, give it an identifier nav-btns, inside it li- our navigation buttons, we will assign a class to them slide-nav-btn, however, we can finish with the markup, let's get down to the styles:


# nav-btns (position: absolute; width: 100%; bottom: 20px; padding: 0; margin: 0; text-align: center;) .slide-nav-btn (position: relative; display: inline-block; list-style: none; width: 20px; height: 20px; background-color: #fff; border-radius: 50%; margin: 3px;) .slide-nav-btn: hover (cursor: pointer;)

Blok nav-btns, in which our buttons are located, we give the property position: absolute, so that it does not stretch viewport in height, because at slidewrapper property position: relative, we set the width to 100% so that using text-align: center center buttons horizontally relative viewport, then using the property bottom we make it clear to our block that it should be at a distance of 20px from the bottom edge.


We do the same with the buttons as with the slides, but now we set them display: inline-block since at display: inline they don't react to width and height since are in an absolutely positioned block. We will make them white and with the help of the already familiar to us border-radius let's give them a circle shape. When you hover over them, we will change the appearance of our cursor for the usual display.


Now let's get down to jQuery - parts:
First, let's declare the navBtnId variable, which will store the index of the button we clicked:


var navBtnId = 0;
$ (". slide-nav-btn"). click (function () (navBtnId = $ (this) .index (); if (navBtnId + 1! = slideNow) (translateWidth = - $ ("# viewport"). width () * (navBtnId); $ ("# slidewrapper"). css (("transform": "translate (" + translateWidth + "px, 0)", "-webkit-transform": "translate (" + translateWidth + "px, 0)", "-ms-transform": "translate (" + translateWidth + "px, 0)",)); slideNow = navBtnId + 1;)));

Here we are when clicking on our slide-nav-btn we call the function, which first of all assigns to the variable navBtnId the index of the clicked button, that is, its ordinal number, since the counting starts from zero, then if we click on the second button, then in navBtnId the value is written 1. Next, we do a check, where we add one to the serial number of the button to get such a number as if the countdown was not from 0, but from 1, we compare this number with the number of the current slide, if they coincide, then we will not take no action, because the desired slide is already in viewport.


If the slide we need is out of sight viewport, then we calculate the distance by which we need to shift slidewrapper to the left, then change the value css transform properties on translate(the same distance in pixels, 0). We have already done this more than once, so there should be no questions. At the end, we save the value of the current slide to a variable again. slideNow, this value can be calculated by adding one to the index of the clicked button.


That's all, in fact, if something is not clear, then I leave a link to the jsfiddle, where all the code written in the material will be provided.




Thank you for the attention!

Tags:

  • jquery slider
  • css
  • css3 animation
  • html
Add tags

This is a responsive touch slider written in jQuery. The engine of this plugin uses CSS3 animations, but at the same time, there are fallbacks for older versions of browsers. Glide.js is simple and lightweight.

Usage

1. Including jQuery

The plugin's only dependency is jQuery, which we need to include in the first place:

2. Connect Glide.js

3. Add html

Let's include the basic styles.

Let's roll up the html slider structure.

4. Initialization

Launch the slider with default settings ...

... or customize it for yourself

Settings

List of available parameters:

Parameter Default value Type of Description
autoplay 4000 int / bool Autoscroll (false to disable)
hoverpause true bool Pause auto-scrolling when hovering over the slider
animationTime 500 int !!! This option works if the browser does NOT support css3. If css3 is supported by the browser, then this parameter must be changed in the .css file !!!
arrows true bool / string Show / hide / attach arrows. True to display arrows in the slider container. False to hide. You can also specify the class name (example: ".class-name") to attach a special html code
arrowsWrapperClass slider-arrows string The class to be assigned to the container with arrows
arrowMainClass slider-arrow string The main class for all arrows
arrowRightClass slider-arrow - right string Right arrow class
arrowLeftClass slider-arrow - left string Left arrow class
arrowRightText next string Right arrow text
arrowLeftText prev string Left arrow text
nav true bool / string Show / hide / attach slide navigation. True to display. False to hide
navCenter true bool Center navigation
navClass slider-nav string Class for the navigation container
navItemClass slider-nav__item string Class for the navigation element
navCurrentItemClass slider-nav__item - current string Class for the current navigation item
keyboard true bool Scroll the slide when pressing the left / right buttons
touchDistance 60 int / bool Touch support. False to disable this feature.
beforeInit function () () function Callback that will run before initializing the plugin
afterInit function () () function Callback that will run after plugin initialization
beforeTransition function () () function Callback that will run before scrolling the slider
afterTransition function () () function Callback that will run after scrolling the slider

API

To use the API, write glide to a variable.

Var glide = $ (". Slider"). Glide (). Data ("api_glide");

Now API methods are available to you.

Glide.jump (3, console.log ("Wooo!"));

  • .current () - Return the current side number
  • .play () - Start autoscroll
  • .pause () - Stop autoscrolling
  • .next (callback) - Scroll forward slider
  • .prev (callback) - Scroll the slider back
  • .jump (distance, callback) - Switch to a specific slide
  • .nav (target) - Attach navigation to a specific element (for example: "body", ".class", "#id")
  • .arrows (target) - Attach arrows to a specific element (for example: "body", ".class", "#id")