A selection of adaptive sliders. Custom image slider using jQuery

Adaptive, or if you prefer, responsive web design is now not just another design trend, it is already a certain standard for website development, ensuring the versatility of websites and harmonious visual perception on the screens of various user devices. More recently, when developing a responsive template, I had to deal with various difficulties in integrating certain sliders and image galleries without disturbing the overall design style. Nowadays everything is much simpler, there are a huge number of ready-made solutions on the Internet and what is especially pleasing is that most of them are freely available, open source.

Due to the variety of tools offered, I have compiled a short overview of the most notable developments of responsive jQuery image sliders that have appeared recently and are distributed without any restrictions, i.e. absolutely free.

WOW Slider

Responsive jQuery image slider with a great set of visual effects (rotation, flyout, blur, spirals, blinds, etc...) and many ready-made templates. With WOW Slider's built-in page insertion wizard, you can easily and effortlessly create stunning slideshows in minutes. The developer’s website contains all the necessary documentation for setting up and using the plugin in Russian, as well as excellent live examples of how the plugin works. A separate Wordpress plugin and a module for Joomla are also available for download. I am sure that many will like this wonderful slider, both beginners and experienced webmasters.

HiSlider

HiSlider - HTML5, Jquery slider and image gallery, absolutely free plugin for personal use on sites running popular systems - WordPress, Joomla, Drupal. With the help of this simple but quite functional tool, you can easily create amazing and vibrant slide shows, spectacular presentations and announcements of new messages on the pages of your websites. Several ready-made templates and skins for the slider, amazing content transition (change) effects, output of various multimedia content: videos from YouTube and Vimeo, flexible user settings, etc...

Nivo Slider

Nivo Slider is a good old one, well known to everyone in the know, one of the most beautiful and easy to use image sliders. The JQuery Nivo Slider plugin is free to download and use and is licensed under the MIT license. There is also a separate plugin for WordPress, but unfortunately it is already paid and you will have to pay $29 for one license. It’s better to do a little magic with the WP theme files and attach the free jQuery version of the Nivo Slider plugin to your blog, since there is plenty of information on how to do this on the Internet.
As for functionality, everything is in perfect order. It uses the jQuery v1.7+ library, beautiful transition effects, simple and very flexible settings, adaptive layout, automatic image cropping and much more.

The idea of ​​the slider was inspired by the developers, who are well-known for the presentation style of Apple products, where several small objects (pictures) change by clicking on the selected category with a simple animation effect. Codrops presents at your disposal a detailed tutorial on how to create this slider, a complete layout of Html markup, a set of CSS rules and an executable jQuery plugin, as well as a wonderful live example of using the slider.

Slit Slider

Full-screen image slider using JQuery and CSS3 + detailed tutorial on integrating the plugin into website pages. The idea is to slice the open current slide with specific content when moving to the next or previous content. Using JQuery and CSS animation you can create unique transitions between slides. The slider's responsive layout ensures that it looks equally good on different types of user devices.

Elastic Content Slider

A content slider that automatically adjusts in width and height depending on the size of the parent container in which it is located. Quite simple to implement and flexible in settings, the slider runs on JQuery, with navigation at the bottom; when the screen size is changed downwards, the navigation is displayed in the form of icons. Very detailed documentation (creation tutorial) and live examples of use.

3D Stack Slider

An experimental version of the slider that demonstrates images with transitions from the 3D plane. The images are divided into two horizontal stacks, using the navigation arrows to change and transition each subsequent image to the viewing state. In general, nothing special, but the idea itself and the execution technique are quite interesting.

A very simple, 100% responsive and full screen jQuery image slider. The slider's operation is based on CSS transitions (the transition property) in conjunction with the magic of jQuery. The max-width value is set to 100% by default, so the size of the images will change depending on changes in screen size. There are no special animation effects or frills in design, everything is simple and designed for trouble-free operation.

Minimal Slides

The name speaks for itself, this is perhaps one of the most lightweight and minimalistic jQuery image sliders that I have come across (1kb plugin). ResponsiveSlides.js is a tiny jQuery plugin that creates a slideshow using elements inside a container. Works with a wide range of browsers, including all versions of IE - the famous brake on progress, from IE6 and higher. The work uses CSS3 transitions in conjunction with javascript for reliability. Simple layout using an unordered list, customization of transitions and time intervals, automatic and manual control of slide switching, as well as support for multiple slide shows at once. This is such a playful “baby”.

Camera

Camera is a free JQuery plugin for organizing slideshows on website pages, a lightweight slider with many transition effects, a 100% responsive layout, and very simple settings. Fits perfectly on the screens of any user devices (PC monitors, tablets, smartphones and mobile phones). Possibility of demonstrating embedded video. Automatic slide change and manual control using buttons and image thumbnail block. An almost complete gallery of pictures in a compact design.

bxSlider jQuery

Another fairly simple responsive slider in jQuery. You can place any content, video, images, text and other elements on your slides. Expanded support for touch screens. Using CSS transition animations. A large number of different variations of slide shows and compact image galleries. Automatic and manual control. Switch slides using buttons and by selecting thumbnails. Small source file size, very easy to configure and implement.

FlexSlider 2

FlexSlider 2 - An updated version of the slider of the same name, with improved responsiveness, minification of the script, and minimization of reflow/redrawing. The plugin includes a basic slider, slide control with thumbnails, built-in left-right arrows and a bottom navigation bar in the form of buttons. The ability to display video in slides (vimeo), flexible settings (transitions, design, time interval), fully adaptive layout.

Galleria

A well known and quite popular responsive jQuery plugin for creating high quality image galleries and sliders. The slider interface, thanks to its control panel, visually resembles a familiar video player; the plugin includes several different design themes. Support for embedded videos and images from popular services: Flickr, Vimeo, YouTube and others. Detailed documentation on setup and use.

Blueberry

A simple, no-frills free jQuery image slider written specifically for responsive web design. Blueberry is an experimental open source jQuery plugin. Minimalistic design, no effects, only smoothly pop-up images replacing each other after a certain period of time. Everything is very simple, install, connect and go...

jQuery popeye 2.1

A very compact jQuery image slider with Lightbox elements. Thanks to its flexible dimensions, it is very easy to integrate into any container, into a single entry in the form of thumbnails, when hovering the mouse cursor or clicking on them, a lightbox with an enlarged picture and controls is activated. It is convenient to place such a slider in side panels to present products or news announcements. An excellent solution for sites with a large amount of information.

Sequence

Free responsive slider with advanced CSS3 transitions. Minimalistic style, 3 design themes, Each frame slides horizontally, appearing in the center, the picture goes to the left, the signature to the right, thumbnails are duplicated in the lower right corner. Pagination of product views to be viewed in each frame. The controls also include back and forward buttons. Supported by all modern browsers.

Swipe

A very simple image slider both in terms of functionality and settings; among the settings there is a change in the speed of changing slides, activation of the manual mode (control buttons are activated), continuous slide show. This slider has the right to exist and it attracted me only because it exists; I didn’t find anything particularly interesting in this development, maybe I wasn’t looking for it well)))

Responsive Image Slider

Such a beautiful, adaptive image slider from Vladimir Kudinov, comrades. A solid, well-designed tool, provided with illustrative examples and detailed instructions for creation, installation and use. Adaptive design, nice buttons and green arrows, everything is quite nice and calm, without pressure.

FractionSlider

Free JQuery slider plugin with parallax effect for images and text slides. Slide animations have multiple display values ​​with full control in each timing and animation setting. The ability to animate several elements on a slide at once. You can set different animation methods, slide fades, or transitions from a specific direction. Automatic display and manual control using navigation arrows that pop up when you hover over the image. 10 types of slide animation effects and much more...

The review turned out to be quite extensive, but not informative enough due to the large number of products considered. You can find out all the details and detailed descriptions of the functionality of a particular plugin directly on the developers’ pages. I can only hope that I have made it easier for someone to find that very necessary tool for creating colorful picture sliders on the pages of their websites.

With all respect, Andrew

Let me start by saying that this article was written to talk about how to create an image scroll slider for web pages. This article is in no way educational in nature, it only serves as an example of how our object of consideration can be implemented. You can use the code provided in this article as a kind of template for similar developments; I hope that I will be able to convey to the reader the essence of what I have written in sufficient detail and in an accessible way.



And now to the point, not so long ago I needed to install a slider on one site, but after searching the Internet for ready-made scripts, I didn’t find anything useful, because some did not work as I needed, while others did not start at all without errors in the console. Use jQuery - plugins For a slider it seemed too uninteresting to me, because... Although this will solve the problem, I will not have any understanding of how this mechanism works, and using a plugin for just one slider is not very optimal. I also didn’t really feel like understanding crooked scripts, so I decided to write my own script for the slider, which I would mark up myself as I needed.


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


Our main object will be viewport, that is, the block in which we will see how our pictures rotate, 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 within the viewport.


Next, on the sides inside viewport, vertically in the middle, there will be back and forward buttons, when you click on them 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 we click on them, we will simply look at the serial number of this button and move it to the slide we need, again by shifting slidewrapper(the shift will be made through changing transform css properties, the value of which will be constantly calculated).


I think the logic of how this whole thing works should be clear after what I have stated above, but if misunderstandings still arise somewhere, then everything will become clearer in the code below, you just need a little patience.


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



As you can see, nothing complicated, block-for-slider serves as just the block in which our slider will be placed, inside it is already viewport, which contains 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 the same size or at least proportions, otherwise the slider will look crooked, because its dimensions directly depend on the proportions of the image.


Now we need to stylize this whole thing; usually styles are not particularly commented on, but I decided to still draw attention to this so that there would be no misunderstandings 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; -ms-user-select: none; -o-user-select: none; position: relative; width: 100% * 4; left: 0; -webkit-transition: 1s; -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, I repeat, is our block on the page, which we will allocate for the slider, its height will depend on its width and on the proportions of our image, because viewport occupies 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 maintained). I placed this element on my page horizontally in the middle, with 100px indented from the top, making its position more convenient for the 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 extends beyond the viewport.


Following css property - user-select:none, allows you to get rid of the blue highlighting of individual slider elements when you repeatedly click on the buttons.


Let's move on to slidewrapper, why position:relative, but not absolute? Everything is very simple, because... if we choose the second option, then with the property viewport overflow:hidden It will seem like absolutely nothing to us, because... myself viewport will not adjust to height slidewrapper, because of which it will have height:0. Why does width matter and why do we set it at all? The fact is that our slides will have a width equal to 100% from viewport, and to arrange them in a line, we need a place where they will stand, so the width slidewrapper must be equal 100% viewport width, multiplied by the number of slides (in my case by 4). Concerning transition And transition-timing-function, then here 1s means that a change is a change of position slidewrapper will happen within 1 second and we will observe it, and ease-in-out– a type of animation in which it starts slowly, accelerates to the middle, and then slows down again; here you can set the values ​​at your discretion.


The next block of properties specifies slidewrapper and its child elements have zero padding, no comments here.


Next we style our slides, their width should be equal to the width viewport, but because 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’ll 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.


Co slide-img It's simple, the image will take up the entire width slide, slide adjust to its height, slidewrapper adjust to height slide, and the height viewport in turn will take the height value slidewrapper, thus the height of our slider will depend on the proportions of the image and the size of the block provided for the slider, which I already wrote about above.


I think at this point we’ve figured out the styles, let’s make a simple slide show without buttons for now, and after we make sure that it works properly, we’ll add and style them.


Let's open our js file, which will contain the slider code, do not forget to connect jQuery, because We will write using this framework. By the way, at the time of writing this article, 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, because we will work with DOM elements that need to be initialized first.


For now we need to declare a couple of variables, one will store the number of the slide that we see at a certain point in time in viewport, I called her slideNow, and the second will store the number of these same slides, this 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, based on our markup, we will see the first slide in viewport.


IN 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, let’s declare it:


function nextSlide() ( )

We will call it in the main block of our code, which we will get to later, 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 currently 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 feed again, from slide 1, which means we change transform css property at slidewrapper on translate(0, 0), thus shifting it to its original position so that the first slide appears in our field of vision, let’s also not forget about –webkit and –ms for adequate cross-browser display (see. css properties reference). After this, don’t forget to update the value of the variable slideNow, telling her that slide number 1 is in view: slideNow = 1;


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


If the first condition is not met, then this indicates that we are currently neither on the last slide nor on some non-existent one, which means we need to switch to the next one, we will do this by shifting slidewrapper to the left by a value equal to the width viewport, the displacement will again occur through the familiar property translate, the value of which will be equal "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, let's tell our slideNow that we see the next slide: slideNow++;


At this point, some readers may be wondering why we didn't 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 adaptive, then, accordingly, the block allocated for the slider is also adaptive, based on this we can understand that when resizing the width of the window without reloading the page (for example, turning the phone on its side), the width viewport will change, and, accordingly, the width of one slide will change. In this case our slidewrapper will be shifted to the value of the width that was originally, which means the pictures will be displayed in parts or not displayed at all in viewport. By writing in our function $("#viewport").width() instead of slideWidth we force it to calculate the width every time we switch slides viewport, thereby ensuring that when the screen width changes sharply, we can scroll to the slide we need.


However, we have written a 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, we can change only one value in the code:


var slideInterval = 2000;

Time in js is indicated in milliseconds.


Now let's write the following construction:


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

Everything couldn’t be simpler here, we’re going through the design $(document).ready(function () ()) We are saying that the following actions must be performed after the document has been fully loaded. Next, we simply 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 perfectly, but if something went wrong for you, then the problem could be either in the version jQuery, or incorrect connection of any files. There is also no need to exclude that you could have made an error somewhere in the code, so I can only advise you to double-check everything.


In the meantime, let's move on, add to our slider a function such as stopping scrolling when hovering the cursor, for this we need to write in the main block of code (inside the $(document).ready(function () ()) construct this 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 the periodic call to the nextSlide function, simply put, we have 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 the cursor over some object, in this case the viewport.


After hovering, I clear the interval, which I indicate in brackets (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 test, we can see how our slider reacts to hover, stopping the slide from switching.


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


First of all, let's mark them:



At first, this markup may be incomprehensible, but I’ll say right away that I wrapped these two buttons into one div with class prev-next-btns just for your convenience, you don’t 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 indicate the sizes of these buttons and using border-radius Let's round the corners so that these buttons turn into circles. Their color will be white, that is #fff, and their indentation 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), this way 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, let's tell our buttons individually that they should be set back 20px from their edges so we can see them in a way that suits us.


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


After styling, our slider should look something like this:


Next, we go back to our js file, where we describe the operation of our buttons. Well, let's add one more 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 whether we are on the 1st slide or not, here we also check whether our slideNow beyond the actual range of our slides and, if any of the conditions are triggered, we will move to the last slide, shifting slidewrapper to the value we need. We will calculate this value using the formula: (width of one slide) * (number of slides - 1), we take all this with a minus sign, because 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 view.


If we are not on the first slide, then we need to move back 1, for this we again change the property transform for slidewrapper. The formula is: (width of one slide) * (number of the current slide - 2), again, we take all this with a minus sign. But why -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, we will again get one by which we have already shifted slidewrapper, so you will need to shift these same widths to 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 simply track whether our buttons were clicked, and in this case we call the functions we need, everything is simple and logical.


Now let’s add slide navigation buttons and return to the markup again:



As we can see, inside viewport a nested list has appeared, let's give it an identifier nav-btns, inside it li– our navigation buttons, we’ll assign them a class slide-nav-btn, however, we can finish with the markup, let’s move on 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; background-color: #fff; 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 the buttons horizontally relative to viewport, then using the property bottom We let our block know that it should be 20px from the bottom edge.


With buttons we do the same thing as with slides, but now we give them display:inline-block, because at display:inline they don't respond to width And height, because are in an absolutely positioned block. Let's make them white and use what we already know border-radius Let's give them the shape of a circle. When we hover over them, we will change the appearance of our cursor for the usual display.


Now let's get started jQuery - parts:
First, let's declare a variable navBtnId, 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 you click on our slide-nav-btn call a function that first assigns to a variable navBtnId the index of the clicked button, that is, its serial number, since the countdown starts from zero, then if we click on the second button, then navBtnId the value 1 is recorded. Next, we do a check, where we add one to the serial number of the button to get a number as if the countdown started not from 0, but from 1, we compare this number with the number of the current slide, if they match, then we will not take any action no action, because the required slide is already in viewport.


If the slide we need is not in sight viewport, then we calculate the distance by which we need to move slidewrapper to the left, then change the value transform css properties to 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 again save the value of the current slide into a variable slideNow, this value can be calculated by adding one to the index of the clicked button.


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




Thank you for your attention!

Tags: Add tags

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

Description of how the slider works.

The slides will be lined up and will scroll 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. Below is shown how the slider works in the forward direction.

When the slider reaches the end, a copy of it 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 slider with automatic scrolling. It requires two containers to operate. The first one will set the size of the visible area of ​​the slider, and the second one is needed to place sliders in it. The slider layout 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 ; )

Container.slider-box specifies the dimensions of the slider. Using the overflow:hidden property, all elements that are not included in the area inside the element are hidden.

Container.slider is set to a larger width. This is necessary so that all the slides fit into the line.

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 carried out by smoothly changing the margin-left property of the container.slider.

$(function () ( var width= $(".slider-box" ) .width () ; // Slider width. interval = 4000 ; // Slide change interval.$(".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. // Container.slider is shifted to the left by the width of one slide. setInterval("animation()" , interval) ; // The animation() function is launched to change slides.) ) ; function animation() ( var margin = parseInt($(".slider") .css ("marginLeft" ) ) ; // Current block offset.slider width= $(".slider-box" ) .width() , // Slider width. slidersAmount= $(".slider" ) .children () .length ; // 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 block.slider returns to the initial position, margin=- width* 2 ; ) $(".slider") .animate (( marginLeft: margin) , 1000 ) ; // Block.slider is shifted to the left by 1 slide. } ;

The result is a simple slider with endless automatic scrolling.

Some time ago, I started learning jQuery. I think everyone knows that this is the name of the most popular library for developing and creating scripts in JavaScript. With its help it is very easy to create spectacular and interactive website elements.

In this article, I want to tell you how to create a simple universal slider using jQuery. In fact, there is a very large number of different ready-made sliders on the Internet, which sometimes look very tempting and are quite functional, but we will make it from scratch.

So, what features of our jQuery slider (which I called HWSlider) can be noted?

  • Ease of use and design - I wanted to create a simple script without bells and whistles, so I did not use CSS3 animations, and the code turned out to be very versatile and understandable.
  • The ability to insert both images and any HTML code into slides.
  • Ability to scroll through slides both in order (forward - back) and select each slide (1,2,3,4...)
  • Automatically generated links (previous - next, and with slide numbers). You just need to insert the required number of divs, and everything else will be calculated by itself. Well, it can be noted that the number of slides is unlimited.

The script is compatible with all modern browsers: IE, Opera, Firefox, Safari, Chrome (since the slider does not use CSS3).

Let's start with the HTML markup. The HTML page or template must be inserted into the desired location.

Here's the content of slide 1
Here's the content of slide 2
Here's the content of slide 3

Everything is simple here, as you can see, you can insert as many slides as you like by creating new divs. You can insert any HTML code inside them, for example a picture or a block of text. Just don’t forget to include the jQuery library itself along with all the js scripts. If you don't know how, look at the example.

#slider-wrap( /* Wrapper for the slider and buttons */ width:660px; ) #slider( /* Wrapper for the slider */ width:640px; height:360px; overflow: hidden; border:#eee solid 10px; position:relative; ) .slide( /* Slide */ width:100%; height:100%; ) .sli-links( /* Buttons for changing slides */ margin-top:10px; text-align:center;) .sli-links . control-slide( margin:2px; display:inline-block; width:16px; height:16px; overflow:hidden; text-indent:-9999px; background:url(radioBg.png) center bottom no-repeat;) .sli -links .control-slide:hover( cursor:pointer; background-position:center center;) .sli-links .control-slide.active( background-position:center top;) #prewbutton, #nextbutton( /* Link " Next" and "Previous" */ display:block; width:15px; height:100%; position:absolute; top:0; overflow:hidden; text-indent:-999px; background:url(arrowBg.png) left center no-repeat; opacity:0.8; outline:none !important;) #prewbutton(left:10px;) #nextbutton( right:10px; background:url(arrowBg.png) right center no-repeat; ) #prewbutton:hover, #nextbutton:hover( opacity:1;)

Let's look at it in more detail. First we give the main block, ID "slider-wrap", the desired width. Since all other blocks are inserted into it, the height does not need to be specified; it will depend on what is inside. Then we need to set the dimensions of the container in which the slides will be located. This is #slider. Let's give it width and height, as well as, for example, a border of 10 pixels. Here the width is 640px, which is less than the width of the parent, since we are adding 10px borders on the right and left. The width of the slides themselves (.slide) also depends on the width of this div.

And the last thing: we need to set position: relative for the slide container since the slides inside are with absolute positioning. For the slides themselves, only the width and height are set in CSS. The remaining properties are set in the jQuery script.

Selector.sli-links is a block that will contain buttons for moving to the required slide. These buttons are simple elements of the form number, which will be inserted in the required quantity automatically, together with their parent.sli-links. For the buttons, we set a beautiful look, namely, we make each button square, align them all in the center, and also, thanks to overflow: hidden and text-indent:-9999px, we remove the text, leaving only background icons, which also change when hovered to this cursor element. For convenience, I used sprites, which reduced the number of images.

Next, the active button is designed. We just change the position of the background. Then we will redesign the links to go to the next and previous slides. You can give them any design, just like buttons. These links are inserted automatically inside #slider. But to make them visible, I gave them an absolute position and a top layer (z-index:3) so they would appear above the slides. I think with CSS everything is clear and simple here: you can change almost all the properties to design the slider the way you need.

Let's now look at the scenario itself:

Var hwSlideSpeed ​​= 700; var hwTimeOut = 3000; var hwNeedLinks = true; $(document).ready(function(e) ( $(".slide").css(("position" : "absolute", "top":"0", "left": "0")).hide ().eq(0).show(); var slideNum = 0; var slideCount = $("#slider .slide").size(); var animSlide = function(arrow)( clearTimeout(slideTime); $ (".slide").eq(slideNum).fadeOut(hwSlideSpeed); if(arrow == "next")( if(slideNum == (slideCount-1))(slideNum=0;) else(slideNum++) ) else if(arrow == "prew") ( if(slideNum == 0)(slideNum=slideCount-1;) else(slideNum-=1) ) else( slideNum = arrow; ) $(".slide").eq( slideNum).fadeIn(hwSlideSpeed, rotator); $(".control-slide.active").removeClass("active"); $(".control-slide").eq(slideNum).addClass("active") ; ) if(hwNeedLinks)( var $linkArrow = $("") .prependTo("#slider"); $("#nextbutton").click(function())( animSlide("next"); )) $( "#prewbutton").click(function())( animSlide("prew"); )) ) var $adderSpan = ""; $(".slide").each(function(index) ( $adderSpan += " " + index + ""; }); $("

").appendTo("#slider-wrap"); $(".control-slide:first").addClass("active"); $(".control-slide").click(function())( var goToNum = parseFloat($(this).text()); animSlide(goToNum )); var pause = function())( if(!pause)(slideTime = setTimeout(function())(animSlide(" next")), hwTimeOut);) ) $("#slider-wrap").hover(function())(clearTimeout(slideTime); pause = true;), function())(pause = false; rotator(); ) ); rotator();

First, the settings are saved in variables: hwSlideSpeed ​​- the speed of turning slides, hwTimeOut - the time after which the slide automatically changes, hwNeedLinks - controls the "Next" and "Previous" links - if the value of this variable is true, then these links will be displayed, and if false , then accordingly they will not be (as on the main page of my blog).

Next, we set the necessary CSS properties for the slides using the .css() method. We stack blocks with slides on top of each other using absolute positioning, then hide them all.hide(), and then show only the first one. The slideNum variable is the number of the active slide, that is, the counter.

The main logic of our jQuery slider is the animSlide function. It takes one parameter. If we pass the strings “next” or “prew” into it, then the conditional operators will work and the next or previous slide will be displayed, respectively. If we send a number as a value, then this number will become the active slide and it will be shown.

So this function hides the current div, calculates a new one and shows it.

Note that the .fadeIn() method, which makes the active slide visible, is given a second argument. This is the so-called callback function. It is executed when the slide appears completely. In this case, this is done to ensure automatic scrolling of the slides. The rotator function defined below calls the animSlide function again to advance to the next slide at the desired interval of time: we will get a closure that ensures constant scrolling.

Everything works fine, but we need to stop the automation if the user moves the cursor to the slider, or presses the buttons. The pause variable is created for this purpose. If its value is positive - true, then there will be no automatic switching. Using the .hover() method, we specify: clear the timer if it is running - clearTimeout(slideTime), and set pause = true. And after moving the cursor, turn off the pause and run the rotator() closure.

Additionally, we need to create new elements on the page and place them in the right place. Using the each() loop for each slide (div with class .slide), we will create a span element inside which there is a number - the number of the slide. This number is used in the animation function to move to the slide with this number. Let's wrap everything in a div with the necessary classes, and in the end we will get the following markup:

It would seem, why do we create markup inside the script, and not in the HTML code? The fact is that, for example, if the user has scripts disabled, he will not see elements that will not work, and this will not confuse him. In addition, the code is simplified, which is good for SEO.

As a result, the slider layout will look something like this (I used images as slides and installed 5 of them):

< >

Below you can see how our jQuery slider works on the demo page and download all the necessary sources.

Finally, a couple of points about the integration of this slider with Drupal. You can add this code to a template file, for example in page.tpl.php, and attach the script as a separate js file to the theme. Jquery in Drupal is enabled by default, but runs in compatibility mode (). There are two options for improvement. Or wrap all js code:

(function ($) ( // All your code... ))(jQuery);

or replace the $ symbols throughout the script with jQuery. Like this:

JQuery(document).ready(function(e) ( jQuery(".slide").css(("position" : "absolute", "top":"0", "left": "0")).hide ().eq(0).show(); var slideNum = 0; var slideCount = jQuery("#slider .slide").size(); var animSlide = function(arrow)( // etc. .

The example has already implemented the first method.

Thanks for reading! Leave comments, come again. You can also subscribe to RSS to receive blog updates first!

Added: That's not all. Read. There we will add new features to this script.

Let me start by saying that this article was written to talk about how to create an image scroll slider for web pages. This article is in no way educational in nature, it only serves as an example of how our object of consideration can be implemented. You can use the code provided in this article as a kind of template for similar developments; I hope that I will be able to convey to the reader the essence of what I have written in sufficient detail and in an accessible way.



And now to the point, not so long ago I needed to install a slider on one site, but after searching the Internet for ready-made scripts, I didn’t find anything useful, because some did not work as I needed, while others did not start at all without errors in the console. Use jQuery - plugins For a slider it seemed too uninteresting to me, because... Although this will solve the problem, I will not have any understanding of how this mechanism works, and using a plugin for just one slider is not very optimal. I also didn’t really feel like understanding crooked scripts, so I decided to write my own script for the slider, which I would mark up myself as I needed.


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


Our main object will be viewport, that is, the block in which we will see how our pictures rotate, 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 within the viewport.


Next, on the sides inside viewport, vertically in the middle, there will be back and forward buttons, when you click on them 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 we click on them, we will simply look at the serial number of this button and move it to the slide we need, again by shifting slidewrapper(the shift will be made through changing transform css properties, the value of which will be constantly calculated).


I think the logic of how this whole thing works should be clear after what I have stated above, but if misunderstandings still arise somewhere, then everything will become clearer in the code below, you just need a little patience.


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



As you can see, nothing complicated, block-for-slider serves as just the block in which our slider will be placed, inside it is already viewport, which contains 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 the same size or at least proportions, otherwise the slider will look crooked, because its dimensions directly depend on the proportions of the image.


Now we need to stylize this whole thing; usually styles are not particularly commented on, but I decided to still draw attention to this so that there would be no misunderstandings 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; -ms-user-select: none; -o-user-select: none; position: relative; width: 100% * 4; left: 0; -webkit-transition: 1s; -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, I repeat, is our block on the page, which we will allocate for the slider, its height will depend on its width and on the proportions of our image, because viewport occupies 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 maintained). I placed this element on my page horizontally in the middle, with 100px indented from the top, making its position more convenient for the 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 extends beyond the viewport.


Following css property - user-select:none, allows you to get rid of the blue highlighting of individual slider elements when you repeatedly click on the buttons.


Let's move on to slidewrapper, why position:relative, but not absolute? Everything is very simple, because... if we choose the second option, then with the property viewport overflow:hidden It will seem like absolutely nothing to us, because... myself viewport will not adjust to height slidewrapper, because of which it will have height:0. Why does width matter and why do we set it at all? The fact is that our slides will have a width equal to 100% from viewport, and to arrange them in a line, we need a place where they will stand, so the width slidewrapper must be equal 100% viewport width, multiplied by the number of slides (in my case by 4). Concerning transition And transition-timing-function, then here 1s means that a change is a change of position slidewrapper will happen within 1 second and we will observe it, and ease-in-out– a type of animation in which it starts slowly, accelerates to the middle, and then slows down again; here you can set the values ​​at your discretion.


The next block of properties specifies slidewrapper and its child elements have zero padding, no comments here.


Next we style our slides, their width should be equal to the width viewport, but because 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’ll 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.


Co slide-img It's simple, the image will take up the entire width slide, slide adjust to its height, slidewrapper adjust to height slide, and the height viewport in turn will take the height value slidewrapper, thus the height of our slider will depend on the proportions of the image and the size of the block provided for the slider, which I already wrote about above.


I think at this point we’ve figured out the styles, let’s make a simple slide show without buttons for now, and after we make sure that it works properly, we’ll add and style them.


Let's open our js file, which will contain the slider code, do not forget to connect jQuery, because We will write using this framework. By the way, at the time of writing this article, 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, because we will work with DOM elements that need to be initialized first.


For now we need to declare a couple of variables, one will store the number of the slide that we see at a certain point in time in viewport, I called her slideNow, and the second will store the number of these same slides, this 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, based on our markup, we will see the first slide in viewport.


IN 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, let’s declare it:


function nextSlide() ( )

We will call it in the main block of our code, which we will get to later, 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 currently 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 feed again, from slide 1, which means we change transform css property at slidewrapper on translate(0, 0), thus shifting it to its original position so that the first slide appears in our field of vision, let’s also not forget about –webkit and –ms for adequate cross-browser display (see. css properties reference). After this, don’t forget to update the value of the variable slideNow, telling her that slide number 1 is in view: slideNow = 1;


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


If the first condition is not met, then this indicates that we are currently neither on the last slide nor on some non-existent one, which means we need to switch to the next one, we will do this by shifting slidewrapper to the left by a value equal to the width viewport, the displacement will again occur through the familiar property translate, the value of which will be equal "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, let's tell our slideNow that we see the next slide: slideNow++;


At this point, some readers may be wondering why we didn't 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 adaptive, then, accordingly, the block allocated for the slider is also adaptive, based on this we can understand that when resizing the width of the window without reloading the page (for example, turning the phone on its side), the width viewport will change, and, accordingly, the width of one slide will change. In this case our slidewrapper will be shifted to the value of the width that was originally, which means the pictures will be displayed in parts or not displayed at all in viewport. By writing in our function $("#viewport").width() instead of slideWidth we force it to calculate the width every time we switch slides viewport, thereby ensuring that when the screen width changes sharply, we can scroll to the slide we need.


However, we have written a 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, we can change only one value in the code:


var slideInterval = 2000;

Time in js is indicated in milliseconds.


Now let's write the following construction:


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

Everything couldn’t be simpler here, we’re going through the design $(document).ready(function () ()) We are saying that the following actions must be performed after the document has been fully loaded. Next, we simply 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 perfectly, but if something went wrong for you, then the problem could be either in the version jQuery, or incorrect connection of any files. There is also no need to exclude that you could have made an error somewhere in the code, so I can only advise you to double-check everything.


In the meantime, let's move on, add to our slider a function such as stopping scrolling when hovering the cursor, for this we need to write in the main block of code (inside the $(document).ready(function () ()) construct this 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 the periodic call to the nextSlide function, simply put, we have 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 the cursor over some object, in this case the viewport.


After hovering, I clear the interval, which I indicate in brackets (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 test, we can see how our slider reacts to hover, stopping the slide from switching.


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


First of all, let's mark them:



At first, this markup may be incomprehensible, but I’ll say right away that I wrapped these two buttons into one div with class prev-next-btns just for your convenience, you don’t 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 indicate the sizes of these buttons and using border-radius Let's round the corners so that these buttons turn into circles. Their color will be white, that is #fff, and their indentation 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), this way 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, let's tell our buttons individually that they should be set back 20px from their edges so we can see them in a way that suits us.


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


After styling, our slider should look something like this:


Next, we go back to our js file, where we describe the operation of our buttons. Well, let's add one more 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 whether we are on the 1st slide or not, here we also check whether our slideNow beyond the actual range of our slides and, if any of the conditions are triggered, we will move to the last slide, shifting slidewrapper to the value we need. We will calculate this value using the formula: (width of one slide) * (number of slides - 1), we take all this with a minus sign, because 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 view.


If we are not on the first slide, then we need to move back 1, for this we again change the property transform for slidewrapper. The formula is: (width of one slide) * (number of the current slide - 2), again, we take all this with a minus sign. But why -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, we will again get one by which we have already shifted slidewrapper, so you will need to shift these same widths to 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 simply track whether our buttons were clicked, and in this case we call the functions we need, everything is simple and logical.


Now let’s add slide navigation buttons and return to the markup again:



As we can see, inside viewport a nested list has appeared, let's give it an identifier nav-btns, inside it li– our navigation buttons, we’ll assign them a class slide-nav-btn, however, we can finish with the markup, let’s move on 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; background-color: #fff; 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 the buttons horizontally relative to viewport, then using the property bottom We let our block know that it should be 20px from the bottom edge.


With buttons we do the same thing as with slides, but now we give them display:inline-block, because at display:inline they don't respond to width And height, because are in an absolutely positioned block. Let's make them white and use what we already know border-radius Let's give them the shape of a circle. When we hover over them, we will change the appearance of our cursor for the usual display.


Now let's get started jQuery - parts:
First, let's declare a variable navBtnId, 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 you click on our slide-nav-btn call a function that first assigns to a variable navBtnId the index of the clicked button, that is, its serial number, since the countdown starts from zero, then if we click on the second button, then navBtnId the value 1 is recorded. Next, we do a check, where we add one to the serial number of the button to get a number as if the countdown started not from 0, but from 1, we compare this number with the number of the current slide, if they match, then we will not take any action no action, because the required slide is already in viewport.


If the slide we need is not in sight viewport, then we calculate the distance by which we need to move slidewrapper to the left, then change the value transform css properties to 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 again save the value of the current slide into a variable slideNow, this value can be calculated by adding one to the index of the clicked button.


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




Thank you for your attention!

Tags:

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