Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Creating a simple carousel using JavaScript
Hari Ram
Hari Ram

Posted on

     

Creating a simple carousel using JavaScript

Hi Developers, In this post, I'm going to show you how to create a simple carousel using Vanilla JavaScript.

It'll be like this,

Carousel

It's live on Github. Check it outhere.

HTML

<main><buttonid="prev">&lt;</button><divclass="card-container"></div><buttonid="next">&gt;</button></main>
Enter fullscreen modeExit fullscreen mode

HTML is really simple here. We've got amain. Insidemain, we've got three elements. One is the actual containercard-container that is going to hold cards and the other two are buttons,#next and#prev.

Card Container

As I said, cards will be inside the card container. In mysite, I used JavaScript to generate cards using an object.

You can check my codehere.

A card looks like this,

<divclass="card view"><divclass="card-image"><imgsrc="./designs/todo.png"alt="TODO App"></div><ahref="https://hariramjp777.github.io/frontend-todo-app/"target="_blank">TODO App</a></div>
Enter fullscreen modeExit fullscreen mode

A card contains acard-image that holds an image and an anchora for the link.

In a card.view class denotes that it is the current card that is being shown on screen.

Here's my simplified CSS for the card.

.card{/* other     styles */opacity:0;pointer-events:none;}.card.view{/* when the card contains .view */opacity:1;pointer-events:all;}
Enter fullscreen modeExit fullscreen mode

The above code block says the card is hidden. It'll be visible only when the class.view is applied.

We've applied.view manually for the first card (as shown above).

That's HTML and CSS. Now we start playing with JavaScript.

JavaScript

First, We're going to select two buttons.

constprev=document.getElementById("prev");constnext=document.getElementById("next");
Enter fullscreen modeExit fullscreen mode

Concept

Say the user clicks thenext button, what we should do?

You guessed it. We have to hide the current card and show the next card. If there's no next card, show the first card.

Same with theprev button, we've to show the previous card. If there's no previous card, show the last card.

In a simpler way,

if prev is clicked    Find the current card.    Check if there is a previous card.    If there, Save the card in a variable called prevCard.    If not, Save the last card instead.    Hide the current card i.e. Remove the class ` .view `    Show the prevCard i.e. Add the class ` .view `
Enter fullscreen modeExit fullscreen mode

Methods we're going to use in JavaScript

MethodsExplanation
.previousElementSiblingreturns the previous element.
.nextElementSiblingreturns the next element.
.firstElementChildreturns the first element (child) of a parent.
.lastElementChildreturns the last element (child) of a parent.

In code, It'll be,

prev.addEventListener("click",function(){/* Find the current card */constcurrCard=document.querySelector(".card.view");/* Set the prevCard based on its availability */constprevCard=currCard.previousElementSibling?currCard.previousElementSibling:document.querySelector(".card-   container").lastElementChild;currCard.classList.remove("view");prevCard.classList.add("view");});
Enter fullscreen modeExit fullscreen mode
next.addEventListener("click",function(){/* Find the current card */constcurrCard=document.querySelector(".card.view");/* Set the nextCard based on its availability */constnextCard=currCard.nextElementSibling?currCard.nextElementSibling:document.querySelector(".card-   container").firstElementChild;currCard.classList.remove("view");nextCard.classList.add("view");});
Enter fullscreen modeExit fullscreen mode

In the second step of both code blocks, I mean setting the card that's going to be displayed, I used the ternary operator, which is an abbreviated way of writing if-else statements.

Let's take an example, In this line of code,

constnextCard=currCard.nextElementSibling?currCard.nextElementSibling:document.querySelector(".card- container").firstElementChild;
Enter fullscreen modeExit fullscreen mode

currCard.nextElementSibling returns the next element of current card (currCard). If it doesn't find any next element, it returnsundefined which is a falsy value in JavaScript.

We're going to use this. If true i.e., we're getting a valid element, set it. Else i.e., we're getting a false value that isundefined, set the first element as the next card.

To get the first element, we can use.firstElementChild.
So,document.querySelector(".card-
container").firstElementChild
will return the first child of.card-container.

That's it. We've got a carousel using Vanilla JavaScript.

Feel free the check the live versionhere.

If you want to check the code, Here's myrepository.

Top comments(8)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jhvanderschee profile image
Joost van der Schee
Author of https://hugocodex.org/
  • Location
    Amsterdam, The Netherlands
  • Education
    Technical University in Delft
  • Work
    owner at Usecue
  • Joined

Thanks for your work. I created something similar (an animated version). You can find it here:codepen.io/joosts/pen/dyKRQZv.

CollapseExpand
 
kemicky profile image
Kemmy Mary Omoshoro
My name is Kemmy Mary, IT graduate (Bsc),ICT-Teacher,competent web developer-fullStack and beginner Mobile App developer. Friendly,focused, hardworking, very flexible and a fast learner.
  • Email
  • Location
    Johannesburg, South Africa
  • Education
    Bsc.IT
  • Work
    Educator-ICT & Software Developer
  • Joined

Hi, why write a carousel in Js when you can easily use bootstrap?
I cant really understand the need for this long, cumbersome Js code for carousel.
May you enlighten me, please. Cheers

CollapseExpand
 
kenovienadu profile image
Ovienadu Ken
Software Engineer at 21CTL
  • Email
  • Location
    Lagos, Nigeria
  • Work
    Full Stack Engineer at 21st Century Technologies
  • Joined

Hello, bootstrap is not the best solution out there. In fact, there are a lot of very useful carousel libraries out there. Sometimes, it's better to understand the flow, and the best way to do it is to build it yourself.

CollapseExpand
 
kemicky profile image
Kemmy Mary Omoshoro
My name is Kemmy Mary, IT graduate (Bsc),ICT-Teacher,competent web developer-fullStack and beginner Mobile App developer. Friendly,focused, hardworking, very flexible and a fast learner.
  • Email
  • Location
    Johannesburg, South Africa
  • Education
    Bsc.IT
  • Work
    Educator-ICT & Software Developer
  • Joined

I do and coding is like Mathematics, there is no one best way of coding ,it depends on you who is coding and your best way and functions you want.
I dnt condemn one coding language for another I just choose which I like best. For those who know how to use bootstrap it has same equal abd more power as that of JavaScript. The down side of JavaScript is if the code is not fired properly your site will remain a mess.
I know what I am asking and I know why I asked and Mr Hari already responded correctly. Thank you

CollapseExpand
 
kemicky profile image
Kemmy Mary Omoshoro
My name is Kemmy Mary, IT graduate (Bsc),ICT-Teacher,competent web developer-fullStack and beginner Mobile App developer. Friendly,focused, hardworking, very flexible and a fast learner.
  • Email
  • Location
    Johannesburg, South Africa
  • Education
    Bsc.IT
  • Work
    Educator-ICT & Software Developer
  • Joined

Hi, I dont think so. It depends in what you want do with it and what you preferences of code is.
And thanks Mr Hari already responded and I have checked the code.

CollapseExpand
 
hariramjp777 profile image
Hari Ram
Hello Everyone, I'm Hari Ram
  • Location
    India
  • Work
    Frontend Developer
  • Joined

Yes, You can use Bootstrap.

I was thinking about creating a carousel using JavaScript. I got this idea using some JavaScript methods (mentioned in the post). I wanted to share this as a blog.

But, Thanks for your comment. Have a nice day.

CollapseExpand
 
kemicky profile image
Kemmy Mary Omoshoro
My name is Kemmy Mary, IT graduate (Bsc),ICT-Teacher,competent web developer-fullStack and beginner Mobile App developer. Friendly,focused, hardworking, very flexible and a fast learner.
  • Email
  • Location
    Johannesburg, South Africa
  • Education
    Bsc.IT
  • Work
    Educator-ICT & Software Developer
  • Joined

Ok,Thank you Mr Hari. I understand now. I checked it out already and got the concept.
Exceptional UI's you got. 👏

Thread Thread
 
hariramjp777 profile image
Hari Ram
Hello Everyone, I'm Hari Ram
  • Location
    India
  • Work
    Frontend Developer
  • Joined

Cheers. Thank you.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hello Everyone, I'm Hari Ram
  • Location
    India
  • Work
    Frontend Developer
  • Joined

More fromHari Ram

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp