Ways to easily modify images using a single button with the help of jq

I am new to programming and eager to learn...

Currently, I am facing the following problem: I would like to create a functionality where three images can be changed using one button and incorporating fadeIn and fadeOut animations. Essentially, all images start as hidden, and upon clicking the button, the first image appears with a fadeIn effect. Upon the next click, the first image disappears and the second image appears, and so on...

This is my HTML setup..

<button id="animeButton">Animate</button> <br>
<img id="firstPic" class="images" src="http://paladone.com/ 
image/cache/data/Pacman/PP2723PM_pac_man_ghost_pixel_bricks-800x800.jpg">
<img id="secondPic" class="images" src="http://i2.wp.com/loyalkng.com/wp-      
content/uploads/2009/05/furious-george.jpg?w=557">
<img id="thirdPic" class="images" src="http://www.wallpaperist.com/ 
wallpapers/Cartoons/Donald-duck-furious-800-600.jpg">

This is my jQuery code...

$(document).ready(function() {
$(".images").hide();    
});

$(document).ready(function(){
$("#animeButton").click(function(){
$("#firstPic").fadeIn(2000);
//Need assistance in implementing further steps....
});
});

Answer №1

To start, make sure to include a data attribute in the following way:

<img id="firstPic" data-id="1" class="images" src="http://paladone.com/ 
    image/cache/data/Pacman/PP2723PM_pac_man_ghost_pixel_bricks-800x800.jpg">

Next,

$(document).ready(function(){
    imgID = 1;
    $("#animeButton").click(function(){
        if (imgID>3) {
           imgID = 1
        }
        $($('[data-id="'+imgID+'"]')).fadeIn(2000);
        imgID = imgID+1
    });
});

Although it hasn't been tested yet, this code should function as intended.

Answer №2

Give this a shot:

$(document).ready(function() {
    $(".pictures").hide();

  var imageArray = ["firstImage","secondImage","thirdImage"];
  // assign attribute to button for next image
  $("#imageButton").attr("nextImage", imageArray[0]);
  var counter = 0;

  $("#imageButton").click(function(){
    var button = $(this).attr("nextImage");
    var currentVisible = $(".pictures:visible").attr("id");
    $("#" + button).fadeIn(2000, function() {
      counter += 1;
      if (counter >= imageArray.length) counter = 0;
      $("#imageButton").attr("nextImage", imageArray[counter]);
    });
    $("#" + currentVisible).fadeOut(2000);
  });
});

Answer №3

Here is a solution for you to try:

$(document).ready(function() {
  $('.images').hide();

  var counter = 0;
  var picArray = [];

  $("div").find("img").each(function(index, value) {
    picArray[index] = $(this);
  })

  $('#animeButton').click(function() {
    if (counter == 0) {
      picArray[picArray.length - 1].fadeOut(2000, function() {
        picArray[counter].fadeIn(2000);
        counter++;
      })

    } else {
      picArray[counter - 1].fadeOut(2000, function() {
        picArray[counter].fadeIn(2000);
        counter++;
        if (counter > picArray.length - 1) {
          counter = 0;
        }
      })
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="animeButton">
  Animate
</button>
<br/>

<div>
  <img id="firstPic" class="images" src="http://paladone.com/image/cache/data/Pacman/PP2723PM_pac_man_ghost_pixel_bricks-800x800.jpg">

  <img id="secondPic" class="images" src="http://i2.wp.com/loyalkng.com/wp-content/uploads/2009/05/furious-george.jpg?w=557">

  <img id="thirdPic" class="images" src="http://www.wallpaperist.com/ 
wallpapers/Cartoons/Donald-duck-furious-800-600.jpg">
</div>

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

Can Javascript be used to open a new window, send POST parameters to it, and pass the request as application/json?

I have a browser client application built with JavaScript that manages a large amount of state data. Sometimes, this data needs to be organized into a structured object and sent to a new window for further processing. Currently, I am using a solution wher ...

Invoke two functions simultaneously on a single Onchange event

Can someone help me understand how to trigger two functions by changing the value of a specific dropdown list using the "OnChange" event in Ajax? Note: The system typically only displays the output of the showhistory() function. Here is my existing code: ...

jQuery UI Slider is malfunctioning (code example included)

I've implemented a jQuery UI slider on my website, and it's functioning quite well. You can check out the slider HERE. However, I've noticed that when I click on 'back to the top', the page smoothly scrolls up. But when I use the ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

How can I incorporate arithmetic operators within a function in EJS?

Currently, I am developing an express app that includes a booking form using ejs with added functionality for payment processing. In the code, I have a select tag where the selected text is stored in a variable. Although console logging shows the value co ...

Solution to ensure fixed header with correct z-index placement

Everything is functioning correctly, except for the issue that arises when scrolling down to view thumbnails. The left bar covers the thumbnail section, making it impossible to select items. I suspect that the z-index of a div is causing this problem. I ha ...

Tips for detecting the existence of a different class within a div/ul through jquery or javascript?

This is how I have my unordered list, or "ul" element, styled. As you can observe, there are two classes defined for the ul <ul class="nav-second-level collapse"> </ul> There might be an additional class added to the same ul like so: <u ...

Using a straightforward approach with v-model in vue.js on an href element instead of a select

Is there a way to utilize an href-link instead of using <select> to switch languages with vue.i18n? <a @click="$i18n.locale = 'en'">EN</a> <a @click="$i18n.locale = 'da'">DA</a> ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

Click to dynamically rotate images using jQuery, or easily swap out images by clicking on them

I am working with 2 images at the moment. My goal is to have the first image visible and the second one hidden initially. When I click on the image, it should switch to display the second image. Clicking again will revert back to the first image. This cyc ...

Angular's Motion Module

Incorporating Angular-5 into my project has introduced a plethora of animations on various pages. While the utilization of jQuery provides a straightforward approach for adding and removing classes to DOM elements, it is frequently advised against using jQ ...

Is there a way to prevent the Pace js plugin from running on page load, but still have it execute during Ajax requests only?

I have successfully implemented the jquery pace plugin with a progress bar theme. Everything is working well, but I am looking to make it run only on ajax requests. I have tried various solutions found through research, but haven't had any luck. Belo ...

Does the success callback for AJAX operate synchronously?

Understanding that AJAX is asynchronous, a common question arises regarding the event execution within the success callback. Consider this scenario: $.ajax({ url : 'example.com', type: 'GET', success : (dataFromServer) { ...

Having trouble retrieving the JSON value as it returns undefined

Having trouble extracting specific values from JSON data. I'm trying to retrieve the value of result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand, but it keeps returning as undefined. To investigate further, I examined the stru ...

Having difficulty accessing $scope beyond the function

One of the functions in my code is called getMail() $scope.getMail=function(){ $http.get(APISource). success(function(data) { $scope.mail =data; }). error(function(data) { console.log("error"); console.log(data); }); } In the succe ...

Protruding button on the surface of the form

I'm struggling with a form layout issue. Here's what it looks like: https://i.sstatic.net/arfJQ.png Removing the mb-3 class doesn't solve the problem, it just removes the spaces between the inputs. How can I make sure the button remains in ...

Position a Bootstrap 3 division within a central division for ultimate centering

I have written a code snippet that looks like this- html, body, .container-table { height: calc(100% - 50px); } /*Centering a div*/ .container-table { display: table; } .vertical-center-row { display: table-cell; vertical-align: middle; } < ...

Obtain the beginning and ending positions of a substring within a larger string

As a beginner in the world of AngularJS and web development, I am faced with a challenge. I have a specific string that is currently selected on a tab, like so: var getSelectedText = function() { var text = ""; if (typeof window.getSelection !== "un ...

Rearrange object based on several criteria - JavaScript

var numbers = { "value": [{ "num1": 1, "num2": 10 }, { "num1": 15, "num2": 13 }, { "num1": 26, "num2": 24 }, { "num1": 6, "num2": 25 }, { "num1": 15, "num2": 20 ...

What is the more effective option: utilizing the bootstrap offset feature or inserting an empty div?

<div class="col-xs-3"></div> <div class="col-xs-6 col-sm-6 col-md-6" style="min-width: 320px;"> </div> OR <div class="col-xs-6 col-md-offset-3 col-sm-offset-3 " style="min-width: 320px;">` </div> I would like to remo ...