The open blogging platform. Say no to algorithms and paywalls.

How to Create a Slider in JavaScript

Learning Web Development in Practice

Like many of you, I believe that learning web development in practice is more effective than bare theory: everything is clear, and the solutions obtained during the development can be used in future projects. That is why I prepared a tutorial on creating a simple image slider with an explanation of each step.

image

This is what the final version will look like:

Note: This article is just a small dive into the world of front-end development because the modern web is not limited to knowledge of HTML / CSS / JavaScript. To become a sought-after web developer, you need to master additional libraries and frameworks, which are often strictly divided between the frontend and backend.

What do you need?

You can download an IDE like WebStorm right away, but when learning web development from scratch, you can start in an online editor as well. We'll be using CodePen, a popular online editor for web developers with instant results. But if you have already started working in any other environment and think that it is much more convenient, just make sure that there is HTML / CSS / JavaScript support.

Writing the code

In various web development courses, familiarity with the front-end begins with a description of the main technologies, namely:

  • HTML is a hypertext markup language used to write the "skeleton" of a site. If we draw an analogy with a house, then this is a frame. Roughly speaking, you build the markup, on which the design will then fall.
  • CSS - Cascading Style Sheets or the very same design. Let's go back to the example with the house: after building it needs to be revetted, painted, made presentable, and it is the CSS that describes the appearance of the site.
  • JavaScript is a programming language that provides functionality. You can interact with things in your home - turn lights, appliances, water on and off, and more. Similarly, you can interact with the site by clicking buttons, hovering over images, and filling out forms. JavaScript handles all of these interactions, and like a scripting language, it can provide rules and logic to determine what should happen next.

HTML

You should start learning web development with HTML, as this is the skeleton of the site. Every HTML document has a standard structure:

<!-- Specifying the type of the current document: -->
<!DOCTYPE html>
<html>
  <! - The content of the <head>
  tag is not displayed on the page, but it helps in work with data and it stores
  information for search engines and browsers: ->
  <head>
    <meta charset="utf-8" />
    <title>Sets the title for the web page window</title>
  </head>
  <! - All displayed content is here: ->
  <body>
    <p>Text</p>
    <img src="URL" alt="Image" />
    <a href="URL">Link</a>
  </body>
</html>

But in our example, there is no need to prescribe the structure of the entire page, because we are working with a separate component, which will then be placed between the tags <body></body>. Everything is simple here: we have the main block (tag <div>), which is a parent and contains three more blocks with different pictures - future slides:

<! - Main slider block ->
<div class="slider">
  <!-- The first slide -->
  <div class="item">
    <img src="https://s3.tproger.ru/uploads/2020/07/field.jpg" />
  </div>
  <!-- The second slide -->
  <div class="item">
    <img src="https://s3.tproger.ru/uploads/2020/07/rose.jpg" />
  </div>
  <!-- The third slide -->
  <div class="item">
    <img src="https://s3.tproger.ru/uploads/2020/07/leaf.jpg" />
  </div>
  <!-- Arrow buttons -->
  <a class="previous" onclick="previousSlide()">&#10094;</a>
  <a class="next" onclick="nextSlide()">&#10095;</a>
</div>

Please note that each tag <div> has its own class. It is for these classes that CSS styling will be applied. In tags, <img> we indicate links to those images that will be shown. In the "onclick" attribute, we refer to a specific JavaScript function by binding a click action to the button.

CSS

In cascading styles, we set the width, height, positioning, color, and animation. In our case, we work separately with the slider container, separately with the image containers that are specified as item, buttons, adding a background to them and animating slides:

/* The slider: */
.slider {
  max-width: 90%;
  /* The position of the element is set relative to its original position: */
  position: relative;
  /* Center horizontally: */
  margin: auto;
  height: 300px;
}
/* The picture is scaled in relation to the parent element: */
.slider .item img {
  /* The element is resized to fill the block and maintain proportions: */
  object-fit: cover;
  width: 100%;
  height: 300px;
}
/* Back and forward buttons: */
.slider .previous,
.slider .next {
  /* Adds an icon to the cursor when it is over the button: */
  cursor: pointer;
  /* The position of the element is set relative to the borders of the browser: */
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  /* Styling the buttons themselves: */
  color: white;
  font-weight: bold;
  font-size: 16px;
  /* Background fading on hover: */
  transition: 0.6s ease;
  /* Rounding the borders: */
  border-radius: 0 3px 3px 0;
}
.slider .next {
  right: 0;
  border-radius: 3px 0 0 3px;
}
/* When you hover over the buttons, add the background of the buttons: */
.slider .previous:hover,
.slider .next:hover {
  background-color: rgba(0, 0, 0, 0.2);
}
/* Slide animation: */
.slider .item {
  animation-name: fade;
  animation-duration: 1.5s;
}
@keyframes fade {
  /* Set and change the transparency: */
  from {
    opacity: 0.4;
  }
  to {
    opacity: 1;
  }
}

We can experiment with all values within the editor. If you have doubts about any of the attributes, just delete it and see what has changed.

JavaScript

A web developer whose training is limited to HTML and CSS is more of a web designer. We're moving on to the main frontend language, which is able to breathe life into a visual solution:

/* Setting the default slide start index: */
let slideIndex = 1;
/* We call the function that is implemented below: */
showSlides(slideIndex);
/* Increase the index by 1 - show the next slide: */
function nextSlide() {
  showSlides((slideIndex += 1));
}
/* Decrease the index by 1 - show the previous slide: */
function previousSlide() {
  showSlides((slideIndex -= 1));
}
/* Set the current slide: */
function currentSlide(n) {
  showSlides((slideIndex = n));
}
/* Flip function: */
function showSlides(n) {
  let i;
  /* We refer to the elements with the class name "item", that is, to the pictures: */
  let slides = document.getElementsByClassName("item");

  /* Checking the number of slides: */
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }

  /* Loop through each slide in a for loop: */
  for (let slide of slides) {
    slide.style.display = "none";
  }
  /* Making an element block: */
  slides[slideIndex - 1].style.display = "block";
}

But do not forget that JavaScript is not unique: modern libraries and frameworks can simplify development and improve the functionality of a web component. For example, Bootstrap allows you to create websites much faster, and even a novice developer can create a working layout using this framework. You can also write a slider in pure HTML / CSS to train your skills in layout and cascading style sheets.

The example given in the lesson is quite simple and is intended to show the possibilities of standard HTML, CSS, and JavaScript interaction.

Image slider ready

The final version of the slider uses several pictures, two buttons with a background change on hover, and smooth transition animation. As you can see from our example, web development training can be based on practice: this not only arouses interest but also allows you to experiment, improve, change the functionality of the components at your discretion, while simultaneously replenishing the knowledge and skills.

Now you can try other ways of implementation, move on to using additional tools like Bootstrap:

You can practice with the slider harder, with additional effects, relying on the code from this project:

Backend and additional features

And if you add a backend to what we've got, you can use the API to use images from other resources, for example, Instagram, or store all the images in your database, without fear that the image will be deleted and the external link will become irrelevant.

But not by practice alone: do not forget to learn theory, so as not to stall for a long time on difficult problems. For this, books or videos are suitable. Web development courses from scratch are also a good way to combine theory and practice.




Continue Learning