What is the best way to incorporate a jQuery progress bar into a slideshow gallery?

My friend and I are working on enhancing our jQuery slideshow by adding a progress bar to show when the gallery will switch to the next image. Here is the code for our slideshow that we have written so far. We would greatly appreciate any help or suggestions. Thank you!

/* Our JavaScript Code */

$('.ppt li:gt(0)').hide();
$('.ppt li:last').addClass('last');
$('.ppt li:first').addClass('first');
$('#play').hide();

var current = $('.ppt li:first');
var interval;

$('#fwd').click( function() {
    moveForward();
    displayPause();
} );

$('#back').click( function() {
    moveBackward();
    displayPause();
} );

$('#stop').click( function() {
    stopSlideshow();
    displayPlay();
} );

$('#play').click( function() {
    startSlideshow();
    displayPause();
} );

function moveForward() {
    stopSlideshow();
    forwardImage();
    startSlideshow();
}

function moveBackward() {
    stopSlideshow();
    backwardImage();
    startSlideshow();
}

function backwardImage() {
    current.fadeOut( 1000 );
    if ( current.attr('class') == 'first' )
        current = $('.ppt li:last');
    else
        current = current.prev();
    current.fadeIn( 1000 );
}

function forwardImage() {
    current.fadeOut( 1000 );
    if ( current.attr('class') == 'last' )
        current = $('.ppt li:first');
    else
        current = current.next();
    current.fadeIn( 1000 );
}

function displayPause() {
    $('#play').hide();
    $('#stop').show();
}

function displayPlay() {
    $('#stop').hide();
    $('#play').show();
}

function startSlideshow() {
    interval = setInterval( "forwardImage()", 5000 );
}

function stopSlideshow() {
    clearInterval( interval );
}

$(function() {
    startSlideshow();
} );

/* The HTML Structure */

        <ul class="ppt">
            <li><img src="images/show_1_banner.jpg"></img></li>
            <li><img src="images/show_2_banner.jpg"></img></li>
        </ul>
        <div id="buttons">
            <button type="button" id="back" title="Previous"></button>
            <button type="button" id="stop" title="Stop"></button>
            <button type="button" id="play" title="Play"></button>
            <button type="button" id="fwd" title="Next"></button>
        </div>

/* Custom CSS Styling */

ul.ppt {position: relative;}

.ppt li {
    position: absolute;
    width:770px;
    height:460px;
}

.ppt img {
    width:750px;
    height:440px;
    margin:0 auto;
    display:block;
    margin-top:10px;
}

Answer №1

http://jsfiddle.net/loktar/AASYC/3/

I made some modifications to the original JavaScript code in order to demonstrate a potential approach for achieving a certain effect. While there are likely more efficient ways to handle passing options, my primary focus was on adjusting the forward function to execute every second. Within this function, it compares the current running time with a specified threshold for changing the image. If the condition is met, the image is swapped; otherwise, a progress bar reflects the percentage of time elapsed.

You have the flexibility to input a starting time in milliseconds, like 8000, or leave it blank for the default value of 5000. By reviewing the code, you should be able to grasp how this functionality can be implemented. To enhance the transition's smoothness and speed, consider animating the width adjustment or shortening the interval below 1000.

Key Modifications:

var interval,
    timeStep = 5000,
    lastTime = (new Date()).getTime();    

function forward() {
    var curTime = (new Date()).getTime() - lastTime;
    if(curTime > timeStep){ 
        lastTime = (new Date()).getTime();
        cur.fadeOut( 1000 );
        if ( cur.attr('class') == 'last' )
            cur = $('.ppt li:first');
        else
            cur = cur.next();
            cur.fadeIn( 1000 );
    }else{
        $("#progress").width(curTime/timeStep * 100 + "%");  
    }
}

interval = setInterval( function(){forward();}, 1000);

Answer №2

In a similar fashion to Loktar's solution, I've previously tackled a task with a method like this:

function moveForward() {

  // ...
  $("#progress").animate({width:'100%'}, settings.interval);
  // ...

}

This function takes care of the sequential progression for you. It operates asynchronously, allowing you to simply call it and move on. You might want to include a

$("#progress").stop().css({width:'0px'});
line within your advance() function to reset the progress bar. This precaution ensures you stay in sync with the image transitions. Experiment with the timing until it feels just right.

Of course, remember to substitute settings.interval with the time interval in milliseconds between each image change. For your particular scenario, I suggest using 4900, considering other tasks like loading high-resolution images may require additional processing time. A delay of less than a hundred milliseconds is likely imperceptible to the human eye.

Answer №3

After incorporating sholsingers sample into Loktar's example, the updated result can be viewed here: http://jsfiddle.net/AASYC/85/

$('.ppt li:gt(0)').hide();
$('.ppt li:last').addClass('last');
$('.ppt li:first').addClass('first');
$('#play').hide();

var cur = $('.ppt li:first');
var interval, progressInterval,
timeStep = 5000,
lastTime = (new Date()).getTime();

$('#fwd').click( function() {
goFwd();
//showPause();
});

$('#back').click( function() {
    goBack();
    //showPause();
} );

$('#stop').click( function() {
   stop();
   showPlay();
} );

$('#play').click( function() {
start();
showPause();
} );

function goFwd() {
    stop();
    forward();
    start();

}

function goBack() {
    stop();
    back();
    start();

}

function back() {
   cur.fadeOut(1000);
    if (cur.attr('class') == 'first')
     cur = $('.ppt li:last');
    else
      cur = cur.prev();
    cur.fadeIn(1000);
    $("#progress").stop().css({width:'0px'});
}

function forward() {
    cur.fadeOut(1000);
    if (cur.attr('class') == 'last')
        cur = $('.ppt li:first');
    else
        cur = cur.next();
    cur.fadeIn(1000);
    $("#progress").stop().css({width:'0px'});
}

function startSlideShow() {
var curTime = (new Date()).getTime() - lastTime;

 if(curTime > timeStep)
 {
    lastTime = (new Date()).getTime();
    $("#progress").stop().css({width:'0px'});
    cur.fadeOut(1000);
    if ( cur.attr('class') == 'last' )
        cur = $('.ppt li:first');
    else
        cur = cur.next();

    cur.fadeIn(1000);
}
else
{
    if($("#progress:animated").length < 1)
    {
        $("#progress").animate({width: "100%"}, 4900);
    }                        
}
}


function showPause() {
$('#play').hide();
$('#stop').show();
}

function showPlay() {
$('#stop').hide();
$('#play').show();
}

function start(changeInterval) {
if(changeInterval){
    timeStep = changeInterval;
}
interval = setInterval( function(){ startSlideShow();}, 500);
}

function stop() {
$("#progress").stop().css({width:'0px'});
clearInterval( interval );
lastTime = (new Date()).getTime();
}

$(function() {
    start();
} );

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

Using Selenium in Java, one can wait for a JavaScript event (such as onchange) to finish before proceeding

When a group of interconnected input fields have an onchange event, the values in some fields are updated correctly while others are not due to interference from the onchange event. Once the onchange event is triggered on a field, it initiates a process t ...

Unable to successfully reset the validity status to true

After implementing server-side validation using the OnBlur event in a form, I encountered an issue where setting the validity of a field to false does not remove the error messages even after setting it back to true. I expected $setValidity true to clear e ...

Grid margin impacted by floated button in Semantic UI

For more information, check out: http://jsfiddle.net/3tL9msap/2 The grid's right margin is being affected by the button's width, pushing it inwards. To see the difference, view the layout without the button at this link: http://jsfiddle.net/3tL ...

Is the submit input type malfunctioning in JavaScript?

I am currently working on creating a dynamic form using JavaScript. The form will present a question with two possible answers, followed by a submit button. Here is the HTML structure I have implemented: <div class="intro py-3 bg-white text-center"> ...

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Inserting a singular image following a designated list item

I have a question that may seem silly, but I'm trying to understand a specific CSS styling issue. I want to add an image targeting a particular li item. Currently, the code adds the image after all the li items: .menuStyling li:after{ content: u ...

How can I customize an SVG using CSS when it's being accessed from another directory on my computer?

I find myself in a bit of a bind at the moment. Within my code lies an SVG depicting a map of the United States. Upon clicking on a specific state, the entire country fades away, revealing a separate SVG displaying only that state. Each of the 50 states is ...

The csurf module in Expressjs is not defined when used within an ES6 function

I have been trying to implement the csurf module within my es6 method, but I am encountering errors in setting it up properly. I have experimented with different ways of declaring it without success and I am unsure of what the issue might be in terms of sy ...

Transmit various data for a single checkbox via AJAX without the need to submit the form

I am facing an issue where I am creating a checkbox form in SQL and trying to send data by clicking on the checkbox, but the data is not being sent. Here is the loop for my checkboxes: <ul> <?php while($objResult = mysqli_fetch_array($objQue ...

Tips for identifying `window is not defined` errors during the build process of your NextJS applications

Currently, I am in the process of transitioning an enterprise application (unable to share code) from Create React App to NextJS using TypeScript. Although I have successfully replaced React Router with Next Routes/Pages, I keep running into the same erro ...

Using an HTML ellipsis without setting a specific width

I am working on achieving a specific layout as shown in the screenshot below. If both SPAN and B fit within the box, they should be displayed one after another. If they do not fit, SPAN should have an ellipsis while B is fully displayed (never larger tha ...

Utilize a Loader with excessively rapid request

Can anyone offer advice on how to handle requests that are too fast to display a loader properly? I currently have a submit button that displays a loader until Firebase responds (ajax request). However, the response time from Firebase is extremely quick ( ...

What is the best method for accommodating various web devices effectively?

Those deciding to close this as not conducive, please read through the entire post. Specific questions will be posed at the end. Seeking practical examples and strategies. Situation As more and more people use devices like smart-phones and tablets to acce ...

Enhancing User Experience with Jquery Dialog and Implementing Stylish Text Presentation

My goal is to design a customer support dialogue that includes a title and two lines of text. The first line should display an error message, while the second line will feature a bold customer service number. To provide further clarity, I have created a vi ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

What is the process for transforming binary code into a downloadable file format?

Upon receiving a binary response from the backend containing the filename and its corresponding download type, the following code snippet illustrates the data: 01 00 00 00 78 02 00 00 6c 02 00 00 91 16 a2 3d ....x...l....... 9d e3 a6 4d 8a 4b b4 38 77 bc b ...

A problem arose during the process of mapping an array of objects in react - There was a parsing error: An unexpected token was encountered, expecting a comma (13:9) with eslint

I am currently working on mapping an array of objects containing data, but I am encountering an error that I am unable to identify in the code. Please disregard the console.logs as they are for my own reference. https://i.sstatic.net/vbpLX.png import Reac ...

Error: The function getAuth has not been defined - Firebase

I have included the code snippets from index.html and index.js for reference. The analytics functionality seems to be working fine, but I am facing an issue with authentication due to an error during testing. Thank you for your help. index.html <script ...

Background color of a scrolling overflow-x panel-primary in Bootstrap

Seeking help with a CSS issue related to a Bootstrap panel. When the overflow-x property is activated, the blue background color of the panel-heading transitions to white instead of staying blue. Any suggestions on how to maintain the blue color while keep ...

Navigating Bootstrap: Refreshing a full-screen modal with a swipe gesture on mobile devices

I'm currently utilizing Bootstrap 5's full screen modal and I'm exploring how to implement a feature that enables refreshing on mobile devices by swiping down, similar to how you would usually refresh a page. <script src="https://cdn.j ...