Using jQuery to animate elements with arrays, variables, and selectors while also incorporating next and previous buttons

Looking to create a Lego instruction animation, but having trouble selecting variables as selectors for the needed animations. When clicking the 'next' and 'back' buttons, I want to animate through the options and count variables sequentially.

In addition, I need the 'reset' button to take me back to the first page of the animation. Any assistance or guidance on this would be greatly appreciated. Thank you.

Click here to see a rough image of how it looks.

$(document).ready(function() {
    var options = ['legs', 'body1', 'cape1', 'cape2', 'head1', 'helmet1']
    var count = 0;

    $('.back').click(function() {
        if (count > 0) { 
            count--; 
            $('selector-name-here').eq(count).animate({ top: '250px' });
        }
    })

    $('.next').click(function() {
        $('selector-name-here').eq(count).animate({ top: '250px' }, 'slow');
        count++;
    })

    $('.reset').click(function() {
        count = 0;
        $('selector-name-here').html('');
    })
});

Answer №1

For a solution to Reset animation in your specific scenario, you can try the code below:

// Reset animation
reset.click(function(){
    for (i = cnt; i >= 1; i--) {
      e = $('.components').find('img')[i];
      $("#" + e.id).stop().animate({ top: top }, {
        complete: function() { $(this).removeAttr('style') }
      });
      $("#" + e.id).removeAttr("style");
    }
    init();
});

Utilizing Jquery

var e;
var top;
var cnt = 0;
var next = $('.next'); 
var back = $('.back');
var reset = $('.reset');
function init(){
  cnt = 0;
  back.addClass( "disable" );
  next.removeClass( "disable" );
  reset.addClass( "disable" );
}
var eleCnt = $('.components').find('img').length;
init();

// Functionality triggered on document ready
$(document).ready(function(){
  // Event listener for reset button
  reset.click(function(){
    for (i = cnt; i >= 1; i--) {
      e = $('.components').find('img')[i];
      $("#" + e.id).stop().animate({ top: top }, {
        complete: function() { $(this).removeAttr('style') }
      });
      $("#" + e.id).removeAttr("style");
    }
    init();
  });

  // Event listener for next button
  next.click(function(){
    back.removeClass( "disable" );
    reset.removeClass( "disable" );
    if(eleCnt > cnt){
      cnt += 1; 
      if(cnt==eleCnt-1){
        next.addClass( "disable" );
      }
      e = $('.components').find('img')[cnt];
      if(e){
        top=$("#" + e.id).css('top');
        $("#" + e.id).animate({top: '248px'});
      } else {
        cnt -= 1; 
      }
    }
  });

  // Event listener for back button
  back.click(function(){
    if(cnt > 0){
      if(cnt == 1){
        back.addClass( "disable" );
        reset.addClass( "disable" );
      } else {
        next.removeClass( "disable" );
        back.removeClass( "disable" );
      }
      e = $('.components').find('img')[cnt];
    }
    if(e){
      $("#" + e.id).stop().animate({ top: top }, {
        complete: function() { $(this).removeAttr('style') }
      });
      $("#" + e.id).removeAttr("style"); 
      if(cnt > 0){cnt -= 1;}
    }
  });
});

For a working example, please refer to this link: https://jsfiddle.net/5zhb60m3/4/

I believe this code snippet will assist you effectively.

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

ngTransclude not encompassing any content whatsoever

I am facing an issue with a custom Angular directive that is used in several of my AngularJS views. The directive is set to transclude, but the wrapped content is not appearing. app.directive('card', [function() { return { restrict: "E", ...

Is there a way to prevent the DOM from loading images until Angular has successfully injected the correct variables?

Having some trouble with this block of code I have: <div class="image" ng-repeat="image in images"> <img src="{{image.url}}"></img> </div> It seems that the image sources are being set correctly, but I keep getting an error wh ...

Executing a command upon the pressing of the enter key within a text input field

Here is my input field: <input type="text" id="word" /> I am looking for a JavaScript function that will be triggered when the user hits enter in this text box. I searched for an answer but couldn't find one that fits my spe ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

The custom styling in custom.css is not taking precedence over the styles defined in

My site is experiencing some element overwriting when I include css/bootstrap.min.css, such as 'a' tags, the .nav bar, and fonts used on the site. Load order: <link href="css/bootstrap.min.css" rel="stylesheet"/> <link rel="styleshe ...

Is there a way to determine if a puppeteer instance is already active?

I have a requirement to run multiple puppeteer scripts simultaneously. Up until now, I've been using separate browsers for each script, but now I want to use just one browser with the ability to run multiple scripts concurrently on different pages. M ...

What is the correct way to position a material-ui icon within a button for proper alignment?

Is there a way to properly align the <ChevronRightIcon> within the <PrimaryButton>? I want it to appear after the button label on the right side. https://i.stack.imgur.com/dcEWo.png <PrimaryButton style={{ paddingRight: &apo ...

What is the best way to modify unchanging text within a span using Jquery?

This is an example of my custom span element in HTML. <span class="k-pager-info k-label">1 - 20 of 91 records</span> I am looking to use Jquery to change "items" to "records" in the above span element. ...

Begin the text movement from the left position, but shift it towards the right

If I have a table width of 100 pixels, I want to create a marquee effect where the text scrolls from right to left starting at 0 pixel position on the left side. The code below currently starts the text from the 100th pixel and moves from right to left: ...

Having trouble opening a local file through a link on a local webpage

I'm encountering an issue with linking to a file on the network through a local webpage. I created a basic HTML page with a hyperlink: <a href="h:\myfiles\dir#1\file1.s">View File</a> When I click on the link, I receive an ...

An interactive scrollable list on Bootstrap 4.1 with flexible 50% height using the

Looking to design a full-screen layout with a top and bottom half. The top half should display a list of items with a scroll bar if it exceeds half of the screen height. After researching, I found a solution using the following structure: <div id="app ...

What is the best way to upload this file in VueJS?

I've come across a file written in outdated syntax that I need to use in a VueJS Component. You can find the file here. For instance, consider these snippets from the file: var CCC = CCC || {}; CCC.STATIC = CCC.STATIC || {}; CCC.STATIC.TYPE = { & ...

How can I retrieve parameters with a true/false response using jQuery Validator Remote?

Currently, I am utilizing the remote method in jQuery validator to check if an email address already exists within our SaaS platform. The script below serves its purpose, but we are interested in enhancing it to retrieve additional information about the e ...

Leveraging web workers for asynchronous API calls

Trying to find an efficient method for utilizing web workers to handle api calls, my current approach involves the following on the client side: - worker-client.js export const workerFetch = (method = "get", url = "/", data = {}) => new Promise((res ...

The onsubmit function is not successfully executing the JavaScript function

This code contains a form for creating a new user login. Upon pressing the 'continue' button, it is supposed to call the 'validateForm()' function which checks the values entered in the form. However, even when there are errors such as ...

Although the XML data retrieval on my localhost is functioning correctly, the webpage experiences issues when transferred to the hosting platform

After successfully running XML data on localhost, I encountered issues when transferring it to the hosting server. Not only was the XML code disabled, but also other PHP and HTML codes were not functioning properly. Has anyone faced a similar problem befor ...

Uh-oh, Ajax encountered a 500 Internal Server Error!

Utilizing ajax to fetch events from my database has hit a snag. Instead of displaying the results, there is nothing visible on the screen, and the console is showing this error message: POST http://www.example.com/system/live_filter.php 500 (Internal Se ...

AngularJs can manipulate the visibility of elements by showing or hiding them based

I wanted to create a simple hover effect where only the child element of each <li> is displayed when I hover over it. Initially, I set up a ng-show value of false for all elements and tried to change it to true on hover. However, this caused all chil ...

Modify the color with JavaScript by manipulating the Document Object Model (DOM)

const elementBox = document.getElementsByClassName('box'); let colorAsStringVariable = '#FEC6F0'; let colorAsNumberVariable = #FEC6F0; Array.from(elementBox).forEach((element) =>{ element.style.backgroundColor = colorAs ...

What is the process for calculating the total sum of dropdown list values?

Here is the JavaScript function I am using: <script type="text/javascript"> $(document).ready(function() { $('#roomOptions select').change(function() { var total = 0; $('#roomOptions select').each(function() ...