Create a simple carousel using only vanilla JavaScript, without relying on any external plugins

Currently, I am working on implementing a carousel using plain JavaScript without the use of any plugins. My goal is to have previous and next buttons that will control the sliding images.

var firstval = 0;

function Carousel() {
    firstval += 2;
    parent = document.getElementById('container-carousel');
    parent.style.left = "-" + firstval + "px";
    if (!(firstval % 150)) {
        setTimeout(Carousel, 3000);
        firstval = 0;
        var firstChild = parent.firstElementChild;
        parent.appendChild(firstChild);
        parent.style.left= 0;
        return;
    }
    runCarousel = setTimeout(Carousel, 10);
}
Carousel();
        #wrapper-carousel {
            position: relative;
            width: 450px;
            height: 150px;
            margin: 0 auto;
            overflow: hidden;
        }
        #container-carousel {
            position: absolute;
            width: 450px;
            height: 150px;
        }
        .child {
            width: 150px;
            height: 150px;
            padding-top: 35px;
            float: left;
            text-align: center;
            font-size: 60px;
        }
        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="wrapper-carousel">
    <div id="container-carousel">
        <div class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0020232_chocolate_cream_gateaux_cake_320.jpeg"> </div>
        <div class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0018904_50_red_roses_in_vase_320.jpeg"> </div>
        <div class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0020232_chocolate_cream_gateaux_cake_320.jpeg"> </div>
    </div>
      <a class="left" href="#wrapper-carousel" style="font-size:100px;z-index:3000;">&lsaquo;</a>
                                        <a class="right" href="#wrapper-carousel" style="font-size:100px;z-index:3000">&rsaquo;</a>
 
</div>

I am looking to include basic buttons to navigate this carousel. No third-party plugin or framework carousel will be used in this implementation.

View my JsFiddle demo here: https://jsfiddle.net/varunPes/wzkLjh8s/21/

Answer №1

A unique custom carousel.

var firstval = 0;
var runSlider;

function CustomCarousel() {
clearTimeout(runSlider);
    firstval += 2;
    parent = document.getElementById('container-carousel');
    parent.style.left = "-" + firstval + "px";
    if (!(firstval % 130)) {
        setTimeout(CustomCarousel, 3000);
        firstval = 0;
        var firstChild = parent.firstElementChild;
        parent.appendChild(firstChild);
        parent.style.left= 0;
        return;
    }
    runCarousel = setTimeout(CustomCarousel, 10);
}
CustomCarousel();


function moveLeft(){
firstval += 2;
    parent = document.getElementById('container-carousel');
    parent.style.left = "-" + firstval + "px";
    
    if (!(firstval % 130)) {
        
        firstval = 0;
        var firstChild = parent.firstElementChild;
        parent.appendChild(firstChild);
        parent.style.left= 0;
        return;
    }
    runSlider = setTimeout(moveLeft, 10);
}

function moveRight(){
firstval += 2;
    parent = document.getElementById('container-carousel');
    parent.style.left =  firstval + "px";
    
    if (!(firstval % 130)) {
        
        firstval = 0;
        var firstChild = parent.firstElementChild;
        parent.appendChild(firstChild);
        parent.style.left= 0;
        return;
    }
    runSlider = setTimeout(moveRight, 10);
}
#wrapper-carousel {
            position: relative;
            width: 450px;
            height: 150px;
            margin: 0 auto;
            overflow: hidden;
            display:flex;
        }
        #main-carousel {
            position: relative;
            width: 450px;
            height: 150px;
            overflow:hidden;
        }
         #container-carousel {
            position: absolute;
            width: 450px;
            height: 150px;
        }
        .child {
            width: 130px;
            height: 150px;
            padding-top: 35px;
            float: left;
            text-align: center;
            font-size: 60px;
        }
        
<div id="wrapper-carousel">
<a class="left" href="#wrapper-carousel" style="font-size:100px;z-index:3000;" onclick="moveLeft()">&lsaquo;</a>
<div id="main-carousel">
    <div id="container-carousel">
        <div  class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0020232_chocolate_cream_gateaux_cake_320.jpeg"> </div>
        <div  class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0018904_50_red_roses_in_vase_320.jpeg"> </div>
        <div  class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0020232_chocolate_cream_gateaux_cake_320.jpeg"> </div>
        </div></div>
  <a class="right" href="#wrapper-carousel" style="font-size:100px;z-index:3000" onclick="moveRight()">&rsaquo;</a>
 
</div>

Create a custom carousel using plain javascript.

Answer №2

It has been noted that a CSS fix is required

<div id="wrapper-carousel">
    <div id="container-carousel">
        <div  class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0020232_chocolate_cream_gateaux_cake_320.jpeg"> </div>
        <div  class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0018904_50_red_roses_in_vase_320.jpeg"> </div>
        <div  class="child"><img width="100" src="https://d2z4fd79oscvvx.cloudfront.net/0020232_chocolate_cream_gateaux_cake_320.jpeg"> </div>
    </div>
      <a class="left" href="#wrapper-carousel"  style="font-size: 100px;z-index: 3050;float: left;position: relative;background: #F3F5F6;top:15px">&lsaquo;</a>
     <a class="right" href="#wrapper-carousel"  style="font-size: 100px;z-index: 3050;float: right;position: relative;background: #F3F5F6;top:15px">&rsaquo;</a>

</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any libraries available to simplify HTML development in C#, .NET, or ASP.NET?

I have a vivid memory of stumbling upon a project where an individual utilized json-like strings to generate high-quality HTML in a certain programming language. Is there a similar tool available for use with C# or .NET? radio-box{ AName, [First|Second| ...

Instant access to an interactive online platform

Is it feasible to create a shortcut from a webpage to my desktop for quick access? For instance, if a dynamic web page has 15 documents and I want to easily create shortcuts to them on my desktop by clicking on each one. I understand this is a brief quest ...

Exchange selection choices among harvested selected boxes

In my project, I am working on swapping all the options between two select boxes. The specific scenario I am dealing with involves recording details of phone calls. These calls can either be inbound or outbound. For outbound calls, I have a 'caller&ap ...

Securing ASP.NET Core applications with iframe authentication cookies

I seem to be facing an issue with my iframe. Whenever I attempt to login, it appears that my authentication cookie is not functioning correctly as I keep getting redirected back to the login screen. How can I resolve this? The cookie operates normally whe ...

Having multiple HTML select elements and utilizing jQuery AJAX

I am looking to implement a dynamic multiple select using AJAX and jQuery. The first select (c1) is functioning correctly. When I click on it, it triggers the appearance of another select (c2). Similarly, clicking on the second select (c2) should lead to ...

Prevent button from being clicked until a certain task is completed using jQuery Steps

i'm currently facing an issue with the jQuery Steps plugin. I need to have the next button disabled until a specific action is completed, and then enable it once the data has been properly validated. My main question is: how can I initially set the n ...

Vue.js encountering an issue of receiving null for the JSON data upon the initial loading phase

Currently, I am expanding my knowledge on vue.js and experimenting with calling a json file to parse the data. Although everything seems to be functioning as intended, whenever I refresh the page, there is a momentary blank screen before the data loads. In ...

Dynamic Character Measurement

I am currently utilizing Datatables to dynamically add rows to a table with 3 columns: Index Text CharCount I am seeking logic to implement a character count for each entry in the 'Text' column and display it in the corresponding 'CharCou ...

What is the best way to apply "display: none;" on a span element nested within a title attribute?

I am utilizing the social-share-button gem to share blog posts on social media. The website has been internationalized, making it bilingual (English and German). Everything is functioning correctly, but I encounter an issue with the social share buttons wh ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Heroku for Node.js

Here is the header setup in my Node.js API app: res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested, Content-Type, Accept Authorization" ); ...

What is the best way to save data in order to effectively showcase a collection of images that together form a single entity in a game

Apologies for the unclear title, I struggled to find the right words. Recently, I delved into the world of 2D game development and was amazed by the capabilities of HTML5's Canvas element. Currently, I am working on my first basic project to grasp th ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Utilizing Angular to integrate with an external API

I have encountered an issue while trying to connect to the Expedia API. In order to do so, I need an API key and ID. Initially, I utilized JSONP for this connection but ran into a bug causing problems. Additionally, storing my API key in JavaScript poses ...

How can we process the incoming data that is in a JSON format?

I'm in the process of creating a Zap that collects customer feedback through Unbird and delivers a coherent Slack message that can be easily understood by anyone within my organization. When importing customer feedback data from Unbird into Zapier, i ...

Having trouble with jQuery AJAX POST request to PHP script for database updating not functioning properly

I am currently in the process of creating a small CMS system and am looking to incorporate AJAX and jQuery into it. Although the code works fine without using AJAX, I am facing issues with data not being passed correctly. The AJAX success message displays ...

Troubleshooting a malfunctioning ember.js HTML output

I'm currently facing a challenging debugging task to figure out why this specific code snippet is failing: Here is the template causing issues: <p class='navbar-text pull-right header-user-info'> {{#if currentUser.isSignedIn}} {{#i ...

Incorporating a File Attachment within a JSON Structure

Can a file attachment be included in a JSON Object? I am working on an HTML Form with text field inputs and a file attachment, and I would like to send all this form data (including the file attachment) as a JSON Object to the server. Are there any specif ...

What is the proper method to adjust the selector on Apify in order to extract information from a JSON data URL?

Utilizing Apify for fetching data from json file links has been my latest project. Here's the json data snippet: <html> <body> <pre> {"exhibitor-single":[{"firstname":"Ines","lastname":"Konwiarz","email":"< ...

Showcasing the selected menu item's value on an Angular button

I've encountered an issue where I have a list of menu items: <md-menu-item ng-value="menuItem.value" ng-repeat="menuItem in filtermenu.menuItems" ng-click="activeFilterCtrl.selectedfilter(menuItem)" translate> <md-button> {{ m ...