What steps should I take to repair my jQuery button slider?

I am facing a challenge with creating a carousel of three images in HTML using jQuery. When the user clicks on the "Next" or "Previous" buttons, I want to scroll through the images one by one. However, I am struggling to hide the other images when one is displayed. If I only have one image in the carousel, it appears correctly styled, but adding the other two images and implementing the button scrolling feature has proven difficult.

Here is the HTML code:


    <div class="wrapper">
        <div class="container">
            <div class="carouselWrapper">
                <div class="carousel">
                    <div class="cImg active" >
                        <img src="../1.jpg">
                    </div>

                    <div class="cImg">
                        <img src="../2.jpg">
                    </div>

                    <div class="cImg">
                        <img src="../3.jpg">
                    </div>
                </div>

                <div id="nav">
                    <div id="button-previous">prev</div>
                    <div id="button-next">next</div>
                </div>
            </div>

And here is the jQuery code:


<script type="text/javascript">
$(document).ready(function(){  
    $('.active').show();

    $('#button-next').click(function(){

        $('.active').removeClass('active').addClass('oldActive');    
        if ($('.oldActive').is(':last-child')) {
            $('.cImg').first().addClass('active');
        } else {
            $('.oldActive').next().addClass('active');
        }
        $('.oldActive').removeClass('oldActive');
        $('.cImg').fadeOut();
        $('.active').fadeIn();
    });

    $('#button-previous').click(function(){
        $('.active').removeClass('active').addClass('oldActive');    
        if ($('.oldActive').is(':first-child')) {
            $('.cImg').last().addClass('active');
        } else {
            $('.oldActive').prev().addClass('active');
        }
        $('.oldActive').removeClass('oldActive');
        $('.cImg').fadeOut();
        $('.active').fadeIn();
    });
});
</script>

Lastly, here is the CSS code:


.carousel img {
    float: left;
    width: 40%;
    height: auto;
    margin: 20px 40px 80px 20px;
}

Answer №1

I'm not sure why you're restricting the image to 40% width, but here's a jsbin I created for you. Your javascript code worked perfectly fine - no changes were needed. Take note of the CSS modifications below:

.sliderContainer {
  width:460px; // set your desired width
  height:300px; // set your desired height
  overflow:hidden;

  .slider {
    width:auto;
    height:300px;
  }
  .sImage {
    float:left;
    width:460px;
    height:300px;
  }
}

Answer №2

Here is the precise solution you have been seeking

<body>
<div class="slider-img">
<div>
<div class="back"><img src ="1.jpg" /></div>
<div class="back"><img src ="2.jpg" /></div>
<div class="back"><img src ="3.jpg" /></div>
<div class="back"><img src ="4.jpg" /></div>
</div>
<div id="button-next"><img src ="next.png" /></div>
<div id="button-pre"><img src ="previous.png" /></div>
</div>
</body>

The CSS code for the above snippet is as follows:

.slider-img { width: 80%; margin:0px auto; height:500px;}
.back{position: absolute;}
#button-next{position:relative; float:right; top:220px; margin-right: 12px;}
#button-next:hover {opacity:0.4}
#button-pre{position:relative; float:left; top:220px;}
#button-pre:hover {
    opacity: 0.4;
}

Jquery Script:

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
    $(document).ready(function(){
    $(".back").first().addClass("active");
    $(".back").hide();
    $(".active").show();
    $("#button-next").click(function(){
    $(".active").removeClass("active").addClass("oldactive");
       if ( $('.oldactive').is(':last-child')) {

        $('.back').first().addClass('active');
        }
        else
        {
         $(".oldactive").next().addClass("active");
        }
     $(".oldactive").removeClass("oldactive");   
     $(".back").fadeOut("slow");
     $('.active').fadeIn("slow");

    });
 $("#button-pre").click(function(){
    $(".active").removeClass("active").addClass("oldactive");
        if($('.oldactive').is(':first-child'))
        {
         $('.back').last().addClass('active');
        }
        else
        {
         $('.oldactive').prev().addClass('active');
        }
    $('.oldactive').removeClass('oldactive');
     $('.back').fadeOut("slow");
     $('.active').fadeIn("slow");
    });


   });


    </script>

I trust that this solution will meet your requirements...

Answer №3

Since the CSS code was not included, I'll explain my approach to achieve this task.

Personally, instead of creating a carousel from scratch, I would opt for using a jQuery or pure CSS carousel plugin. But if starting from scratch is a requirement, I would keep it simple by cycling through images with just one image tag, as shown below:

HTML

<div class="image-wrapper">
    <img src="" id="carousel" />
</div>

Then, I would utilize JavaScript to switch between images:

Javascript

var images = [
    "image/url/1.png",
    "image/url/2.png"
];

var selectedImage = 0;

$(document).ready(function(){
    $("#carousel").attr("src", images[0]);
});

function goForward(){
    selectedImage += 1;

    if(selectedImage >= images.length){
        selectedImage = 0;
    }

    $("#carousel").attr("src", images[selectedImage]);
}

function goBackward(){
    selectedImage -= 1;

    if(selectedImage < 0){
        selectedImage = images.length - 1;
    }

    $("#carousel").attr("src", images[selectedImage]);
}

To navigate between images, create buttons in HTML that call goBackward(); and goForward();, like so:

More HTML

<button onclick="goForward();">Forward</button>
<button onclick="goBackwward();">Backward</button>

You can further enhance the appearance of the carousel by adding custom animations and transitions using jQuery. Feel free to style it according to your preference. The possibilities are endless!

JSFiddle

Check out my JSFiddle example here.

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

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Issue with jQuery: The click event handler is not firing on elements that were previously hidden

$(document).on('click', '*', function (e) { alert('clicked'); }); I have a script that works for all elements on the current page. However, when I click an element that reveals a previously hidden div element, the click e ...

Tips for setting up a bookmark in bootstrapvue

Hello everyone, I am currently working with bootstrapvue and I need help figuring out how to add a favorite icon. The documentation only provides icons for rating systems. I have a list of reports and I want users to be able to mark their favorites, simil ...

Creating a flexible grid layout in CSS without relying on any pre-made frameworks

Suppose I am working with the following HTML structure <div class="option"> <input type="checkbox" /> <label>Checkbox</label> </div> <div class="option"> <input type="checkbox" /> <label>Chec ...

Steps to create a thumbnail image following the insertion of an image into an input type="file" within a form, and subsequently submitting both elements on the form together

Currently, I am working on a form that enables users to upload images. Once the user submits the form, my goal is to create thumbnails for each image on the front-end and save them on the server afterwards. Due to security restrictions, changing the value ...

What is the best way to append something to the textContent property of an HTML tag within a markup page?

While working on resolving an XSS vulnerability in the jqxGrid where the cell content is rendered as HTML, I encountered a scenario like this: <a href="javascript:alert('test');">Hello</a>. To address this issue, I am exploring ways t ...

Alignment issue: Center alignment failing to work correctly

I'm currently working on a navigation bar with a central title and links to other pages aligned to the right. Despite using text-align: center, the title remains off-center. I've implemented a flexbox to ensure that the title and links are on the ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Nightwatch.js feature not functioning properly in a 'closing' manner

I'm facing an issue where I need to execute a function at the beginning of my test before proceeding with the rest of the test steps. Here is the custom command I am using, named internalAdviceLinksHtml: const solr = require('solr-client') ...

Redirecting pages without a hash portion

In my Express.js app.js file, there is a get route that looks like this: app.get('/admin', function(req, res, next){ if(req.isAuthenticated()) { return next(); } res.redirect('/admin/login'); },Routes.Admin.Index); When a ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

Update CSS using onChange event with an array of values

I'm currently working on an app that allows users to select a color scheme from a dropdown form. The hexidecimal values associated with the selected color scheme successfully populate specific text fields as intended. However, I am facing difficulty i ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

Generate a visually dynamic representation of a live website page

I'm curious if it's possible to create a login page similar to the one shown in this image, using HTML, CSS, and Javascript. Instead of a traditional background image, I want the background to display the actual layout of another website, such a ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

What is the best way to retrieve the current URL of an external page that is loaded within a jqModal window?

Can the current URL of an external page loaded in a jqModal window be accessed? Additionally, where is the external page located within the jqModal implementation - in an iframe or div? ...

Delay the next loop iteration until receiving an HTTP request

I have a task where I am collecting YouTube video IDs and storing them in an array. Then, I am looping through each video ID to determine the size of that ID's thumbnail image. My challenge now is making sure my loop waits for the HTTP request to fini ...

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

Creating a Related Entry in strapi v4: A Step-by-Step Guide

Whenever I try to add a new record in my Collection-Type, all the field values are successfully added to the new entry except for the value in the field with a Relation type. For instance, in my event Collection-Type, I have fields like name, performers, ...

Resolving negative margin issues in Material UI components through detailed textual guidance

Having an issue with the paragraphs in material-ui components. The problem arises when the text exceeds the dimensions of the component, causing it to spill over as shown in the image below. <Grid container wrap="nowrap" css={[borde,{ ...