Initiate a fade-in/fade-out slider when the button is clicked

I have successfully developed a fadein/fadeout slider that automatically transitions between images. However, I am now looking to implement the functionality to manually play the slider by clicking on next/prev buttons.

HTML

<section class="wrapper">
<ul class="slider">
    <li><img src="http://www.tylershields.com/images/gallery/art_gallery.jpg" alt="" /></li>
    <li><img src="http://www.goa-tourism.com/images/photogallery/1287634889_pid_kala%20academy%20art%20gallery.jpg" alt="" /></li>
    <li><img src="http://www.magnoliabakery.com/uploads/GalleryImageModel/105/filemask/mag1003_magnolia_fall_14original.gallery.jpg" alt="" /></li>
    <li><img src="http://www.lancasterconventioncenter.com/_images/_gallery/gallery15.jpg" alt="" /></li>
</ul>
<button data-dir="prev">Prev</button>
<button data-dir="next">Next</button>
</section>

CSS

*               {margin:0; padding:0;}
.wrapper        {width:800px; margin:0 auto; max-width:100%;}
.slider         {position:relative;}
.slider li      {position:absolute; top:0; left:0; list-style:none; width:100%; opacity:0;}
.slider li img              {width:100%;}
.slider li:first-child      {position:relative; display:block; opacity:1;}

Script

var current = 0,
    elem    = $('.slider li'),
    slides  = $('.slider li').length,
    speed   = 3000,
    transSpeed = 1000;

function autoSlide(){

    current = (current == (slides-1)) ? 0 : +1;

    $('.slider').find('li')
        .filter(':eq('+ current +')').addClass('current').animate({'opacity':1}, transSpeed)
        .siblings('li').removeClass('current').animate({'opacity':0}, transSpeed);
    };

var timer = setInterval(autoSlide, speed);

$('button').on('click', function(){
    clearInterval(timer);
     autoSlide();
     timer =setInterval(autoSlide, speed);
});

Fiddle Demo

Answer №1

The issue lies within this specific line of code:

current = (current == (slides-1)) ? 0 : current + 1 // The problem was caused by the incrementing logic, which always set the value to 1

As a result of this line, your current variable was consistently assigned a value of 1.

I hope that this clarification proves helpful!

Fiddle Demo


Update:

In order to enable movement both forwards and backwards, it is necessary to determine which button has been clicked since you are utilizing a single function for handling both actions. Please refer to the modified code below:

You can pass the clicked element to the autoSlidefunction(element) as shown below:

Complete Code:

function autoSlide(element) {
    var clicked = $(element).text().toLowerCase().trim(); // Identify next or previous
    if (clicked == "next")
        current = (current == (slides - 1)) ? 0 : current + 1; // Increment current value
    else
        current = (current == 0) ? 0 : current - 1; // Decrement current value
    $('.slider').find('li')
        .filter(':eq(' + current + ')').addClass('current').animate({
            'opacity': 1
        }, transSpeed)
        .siblings('li').removeClass('current').animate({
            'opacity': 0
        }, transSpeed);
};

var timer = setInterval(autoSlide, speed);

$('button').on('click', function () {
    clearInterval(timer);
    autoSlide($(this)); // Pass clicked element to autoSlide()
    timer = setInterval(autoSlide, speed);
});

Updated Fiddle

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

Having trouble with a switch statement in Javascript that is unable to find a case for "none."

In my code, I am checking to see if there is a ball in a specific map point and then changing the color of the pixels where the ball is located to match the color of the ball. Here is my code snippet: function UpdateColorInMapPoints(mapPointIndexs) { / ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Fetching client-side data in a Functional Component using Next JS: The proper approach

I have a functional component that includes a form with existing data that needs to be populated and updated by the user. Within this component, I am using a custom hook for form handling. Here is an example: const [about, aboutInput] = useInput({ t ...

Is it possible to link to a .json file stored on my server and then create a template for it?

I have set up a Webserver on kasserver.com, and I have a PHP script that retrieves data from an API every 15 minutes and saves it on my Webserver. Now, I am looking to create a template for the saved JSON data, but I am having trouble accessing it locally. ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Ensure that two div elements expand to occupy the available vertical space

I am looking to create a layout similar to the following: |---| |------------| | | | b | | a | |____________| | | |------------| |___| |______c_____| Here is the code I have so far: <table> <tr> <td class="leftSid ...

Polyfill for window.showOpenFilePicker function

Could anyone recommend a polyfill for the window.showOpenFilePicker method? For reference, you can check out the documentation on MDN. ...

Easy Div Centering with jQuery Toggle for Internet Explorer 6

Press the button to center the div, press it again to align it to the left. This feature is compatible with all browsers except for IE6, which does not support margin: 0 auto;. How can I find a solution to this issue? The width of the div is not fixed and ...

The jQuery this() function encounters issues with Firefox browsers

Here is my code snippet: <script type="text/javascript"> jQuery('.element').hover( function () { jQuery(this).find('div.thumbnail-meta-data-wrapper').show(); jQuery(this).find('div.thumbnail-meta-data-wrapper&a ...

Is it possible for Monaco Editor to accommodate nested tokens?

I have configured a custom language in the monaco editor, with two root tokens: [/^\[?[e|E][r|R][r|R][o|O][r|R]\]?\s.*/, 'error'], [/\d{1,4}(-|\/|\.|:)\d{1,2}\1\d{1,4}/, 'time'], Using this ...

Magento theme installation on the website encountered unexpected obstacles

Hi everyone, I'm currently in the process of constructing a website with Magento. However, I've encountered some issues after trying to install a theme. It seems like certain files, including CSS, are not loading properly. To provide better conte ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

What is the best way to ensure that a React app is always displayed in full screen

I am facing an issue while developing an app with React and Material UI. I am trying to display the app in full-page mode, but unable to achieve it successfully. Currently, it appears like this: https://i.sstatic.net/Hg0CA.png Here is my code snippet from ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Error in Javascript when attempting to embed Redbubble

Hello, I am currently working on embedding the redbubble code into a Joomla site for a client who has a Redbubble store. However, I seem to be encountering some issues with the script. <script type="text/javascript" src="http://www.redbubble.com/asse ...

Warning: The React Router v6's Route component is unable to find the origin of the key props

I recently came across an error in my console and I'm unsure which list is causing it. Is there a way for me to trace back the origin of this error so I can pinpoint where to fix it? The error seems to be related to the React Router component, which ...

JQuery: Issue with SVG not moving along with parent div

I have a situation where I am loading an SVG into a div using jQuery. The div has a CSS property of `position: absolute`. After setting the div to `position: left`, I noticed that only the div moves and not the SVG inside it. How can I make both the div a ...

Please explain the purpose of the .forEach statements listed below

Describe the functionality of the two forEach loops provided in the code snippet below. Also, is 'col' a predefined property for arrays? var width = data.length, height = data[0].length; data.forEach(function(col){ col.forEach(function(v ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Managing element IDs with colons in jQuery

We are encountering difficulty accessing the div element with ID "test: abc" using jQuery in our JS code. <div id="test:abc"> $('#test:abc') Without the colon, everything works perfectly fine. Unfortunately, we do not have control over t ...