An Image Carousel slider with JS

in Programming & Dev3 years ago (edited)

I already have my website up and going, I am using Github to host the code so anyone who wants to read it can do so, sort of like with any open source project. Hopefully this opens up my chances of getting a job sooner rather than later, although I am not actively searching at the moment.

Right now I am just grinding, grinding, grinding. When we are talking code, it all comes down to grinding. The more you grind, practice your skills, find out about new tweaks, practice what you should already know by heart, and just putting your code to work... the more you will learn.

I am already pretty efficient with my HTML and CSS code, I still need a lot of practice and a hell lot to learn regarding JavaScript - and don't worry, I've been taking my lessons religiously even though I haven't posted about JavaScript for something like two weeks; but the point is, these little projects are mainly about HTML and CSS and grinding my skills.

Image Carousel

I will build an image carousel that will slide through images automatically, but it will also have a NEXT and PREV image buttons. It is a simple project, but necessary for any interactive website out there.

HTML Code

  <body>
    <div class="carousel">
      <div class="image-container" id="images">
        <img
          src="https://images.hive.blog/768x0/https://images.ecency.com/DQmWD6Vn7xQmKkwsZHiMoEfatf4mXJgTafKjeJFr2WL4Pdb/dsc_0220.jpg"
          alt="first-image"
        />
        <img
          src="https://images.hive.blog/768x0/https://images.ecency.com/DQmT4eJgNEg4X2kKRhvFx5g4d2MBg4cMtPNKbMWbhzNDdqH/dsc_0218.jpg"
          alt="second-image"
        />
        <img
          src="https://images.hive.blog/768x0/https://images.ecency.com/DQmcyJVawVcHKV1oAcykNnvFq7Rh5SCifWqd98hZ48HTSkY/dsc_0186.jpg"
          alt="third-image"
        />
        <img
          src="https://images.hive.blog/768x0/https://images.ecency.com/DQmRmfktjy1MoqzkG4Xa2uv46xr9JiHFB6yZwpBUq7pVxru/dsc_0208.jpg"
          alt="fourth-image"
        />
        <img
          src="https://images.hive.blog/768x0/https://images.ecency.com/DQmVFbJPDKhAqi8baNvYH9SDPRNmNNbdVsAwQpTpYkee7xT/dsc_0185.jpg"
          alt="fifth-image"
        />
      </div>
      <div class="buttons-container">
        <button id="left" class="btn">Prev</button>
        <button id="right" class="btn">Next</button>
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

As always, the result after the HTML Code is shitty and is not even worth including it, but it is also nice to see how easy and simple it is to get from crap to working wonder in no time.

image.png

CSS Code

* {
  box-sizing: border-box;
}

body {
  font-family: "Roboto", sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

.carousel {
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
  height: 430px;
  width: 600px;
  overflow: hidden;
}

First I want to set the images to the same size, then I also want them to fit the container perfectly.

img {
  width: 600px;
  height: 400px;
  object-fit: cover;
}

After this code, the carousel only displays one image, but the top of the second image still shows below the first one, in order to no show it I just need to set the display property as flex and the items will align horizontally.

.image-container {
  display: flex;

Now, I want to move the image to display using the X axis, using the transform:translateX property.

  transform: translateX(0);

I set it to 0 and with the Javascript I'll modify this value

  transition: transform 0.5s ease-in-out;
}

.buttons-container {
  display: flex;

Each button is a flex item now.

  justify-content: space-between;
}

All the space will be put in between the items.

Now we are beginning to have something real and concrete that doesn't look like a piece of crap.

image.png

.btn {
  background-color: rgb(231, 22, 22);
  color: #fff;
  border: none;
  padding: 0.5rem;

Remember that REM units are just a multiplier of the root HTML element, which by default is 16 px.

  cursor: pointer;
  width: 49.5%;
}

.btn:hover {
  opacity: 0.75;
}

.btn:focus {
  outline: none;
}

This is how it looks now, it is actually a work in progress now and despite it being so simple (yeah, it is just the carousel without any background or other features) it is already looking slick.

gif1.gif

JavaScript Code

The functionality for this website is pretty simple, in fact I have already done similar things before and posted on Hive, but it still very educational to go through it, perhaps using different ways

Let's bring the images container

const images = document.getElementById("images");

And also bring the buttons

const leftBtn = document.getElementById("left");
const rightBtn = document.getElementById("right");

I also want to get each individual image as well

const imageArray = document.querySelectorAll("#images img");

We get inside the images-container, and then fetch each image

I then set an index of where I am at on the image array, I use let to modify it later

let index = 0;

let interval = setInterval(run, 2000);

setInterval takes in a function which I call run

function run() {
  index++;
  changeImage();
}

function changeImage() {
  // First I reset the index to 0
  if (index > imageArray.length - 1) {
    index = 0;
  } else if (index < 0) {
    index = imageArray.length - 1;
  }

  images.style.transform = `translateX(${-index * 600}px)`;
}

The automatic slider is working perfectly now, but I still need to fix the buttons so the user can change the image at will.

gif2.gif

First of all, if I want the buttons to work smoothly I need to reset the automatic sliding time each time the user clicks one of the two buttons, right?

function resetInterval() {
  clearInterval(interval);
  interval = setInterval(run, 2000);
}

Having determined that function I can add an event listener to each button and use the resetInterval function.

rightBtn.addEventListener("click", () => {
  index++;

  changeImage();
  resetInterval();
});

For the next button I increment the index, for the prev button I decrement the index.

leftBtn.addEventListener("click", () => {
  index--;

  changeImage();
  resetInterval();
});

gif3.gif

And Voila! The Image slider Carousel is working perfectly! This little piece of code can be used with whatever quantity of pictures you want, it works all the same. You can also modify the interval in which each photo changes, it's just a matter of taste at this point.




These projects are based on a CSS, HTML and JS paid course I got on Udemy by Brad Traversy. I made my own changes and tweaks but the template so to speak, is his idea and I do not claim them to be my own. If you are looking to practice CSS and JavaScript, his courses are the way to go, check them out on Udemy.

Sort:  

Nice work @anomadsoul. You can checkout swiperJS it's makes creating sliders on web pages much more better and easier. Works with frontend frameworks like react, VueJS, AngularJS and even a regular webpages built without frameworks. It's also well documented. Ever since I tasted swiperJS I stopped using carousel for sliders. You can click here for more info.

Damn this is a great resource, I appreciate it man! I will definitely look more into it.

Nice =) Link for the repo? Would love to check it out

yeah man, I still don't have anything there yet, but the website ericflor.es is hosted on /ericfna's GitHub and I will have all my code there (there just isn't any yet lol)

edit: just noticed I said on the post it is already up and going, I should've said it is up but still nothing there yet. I have the code and everything I want to add but I know it will be a long day when I decide to upload everything (I have bits and pieces everywhere, need to make it into a single project)

Neat! I wish I understood coding better to make use of such things. 👍

Dropping you some hot !PIZZA and !LUV on this post!

Thanks for the pizza man! I actually have a whole post series about javascript, CSS and HTML in case you want to learn from the beginning.

Love your work mate. Just curious to know how long this took to make? I have absolutely no clue when it comes to programming so just interested.

This small project took me less than 40 minutes, what drains most of the time is learning, once you know how to do stuff it is actually quite fast and simple (I have like 200 hours of learning, there are people with thousands of learning hours)