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

Is there a way to postpone these animations without relying on setTimeout?

As I develop a single-page website, my goal is to smoothly transition between sections by first animating out the current content and then animating in the new content. Currently, I have achieved this using setTimeout(), where I animate out the current con ...

Events triggered by JQueryUI's .selectable functionality

I am facing a minor issue with the JQuery .selectable function. My goal is to bind events to each tab. I have successfully handled the click event for each tab, but I'm struggling when it comes to selecting two or more tabs. For instance, if I clic ...

Is it possible to refresh only a specific table on a Razor site without reloading the entire page?

Greetings! I am currently working on a table and facing an issue. Currently, I am unable to update the table without the website refreshing. I require a solution that will allow me to easily Add, Delete, or Modify rows in the table's content. This ...

Encountering a MySQL error upon inputting an apostrophe into the form

I'm facing an issue where I can't save a form with an apostrophe to the Database. Here's the code I'm using: <?php $abouttitle=$_POST[abouttitle]; $aboutcontent=$_POST[aboutcontent]; $aboutside=$_POST[aboutside]; $abouts ...

implementing automatic ajax requests when user scrolls

This is a piece of JavaScript code: $(window).scroll(function() { $.ajax({ type: "GET", url: "not_data.php", data: dataString, success: function my_func () { //show new name ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

Creating JSON objects for ASP.net MVC 4 AJAX calls: A Guide

Upon discovering vsdocs files, I envisioned a way to incorporate intellisense into my JQuery files for handling objects sent to my ASP.net MVC backend. It's like having an MVC Model specifically for jQuery Ajax callbacks. You can find the following ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

Using Backbone.js to Retrieve Data from the Server and Bind it to a Model

Having recently delved into Backbone.js, I found this informative tutorial quite helpful in getting started. Now, I am looking to take things a step further by fetching data from the server instead of hardcoding values in JavaScript as demonstrated in the ...

Increase scrolling speed? - Background abruptly moves after scroll

I'm facing a minor issue. I want to create a parallax background effect similar to what can be seen on nikebetterworld.com. In my initial attempt, I managed to achieve some functionality, but I believe it can be improved. As I scroll, the background p ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Exploring Next.js: A beginner's attempt at displaying basic JSON data

I'm having trouble updating and displaying the content of my JSON data in my React app. Despite trying various solutions, including adjusting the return value of functions and seeking help on forums, I still cannot get rid of the issue where an empty ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

AngularJS to validate image dimensions (width and height) on upload

Hello, I am new to working with Angular JS. I have been experimenting with a login form that includes a file upload field for the user picture. The input field code looks like this: <input type="file" file-model="userPic"/> When I submit the form i ...

Adjust the clarity of the elements within my HTML document

I have been working on creating a login page that will appear in front of the main webpage. Through my online research, I discovered a technique to blur the main webpage background until the user logs in. Below is the code snippet: HTML: <div id="logi ...

The arrow icon that I included in my bootstrap project seems to have disappeared from my view

While trying to enhance my footer, I attempted to include an arrow-up-circle icon. However, after adding the code, the icon doesn't appear. Here is the html snippet I used: <html> <head> <link href="https://cd ...

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...

Library for creating custom password input fields with a text type

We are currently facing an issue on our website where autofill is not working correctly due to having two password input fields - one for login and one for the password. Browsers are unable to remember the login information and paste the password into th ...

The jQuery ajax call is returning some undefined results, which is in contrast to the network response, which appears to be completely accurate

My system utilizes an oracle-db and a php-script that is triggered by a query ajax-call. Here is the php-script: $query = 'SELECT pl.event_id, pl.og2, d.name dst, pl.state, pl.note, pl.createdate FROM publevels pl LEFT JOIN dst d on (d.og2 = pl.og ...

Issues with the event firing in the Polymer component for google-signin?

I recently set up a new starter-kit project using polymer-cli 1.7 and I'm attempting to incorporate Google authentication utilizing the google-signin element. Although the sign in button appears and works for signing in, the signedIn property isn&apo ...