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

Enhancing User Experience with AJAX and JSON in Servlet JSP Applications

I've been working on my school project for a while, but I'm having trouble with the login page. Every time I try to log in, I receive a PARSING ERROR message like this: Error Login AJAX For the login process, I am using a simple servlet that co ...

What is the best way to invoke a function from one controller in angularjs to another controller?

I am trying to implement a solution where I need to call the Listing function of testController from userController. I have placed a marker (//) in the code snippet below to indicate where I want to make this function call. This implementation is being d ...

Identify the geometric figure sketched on the canvas using the coordinates stored in an array

After capturing the startX, startY, endX, and endY mouse coordinates, I use them to draw three shapes (a line, ellipse, and rectangle) on a canvas. I then store these coordinates in an array for each shape drawn and redraw them on a cleared canvas. The cha ...

What is preventing this Javascript from running in Firefox and Chrome?

I recently encountered an issue with some Javascript code that functions correctly in Internet Explorer, but fails to work on Mozilla Firefox or Google Chrome. Any insights as to why this might be the case? function returnData(strCode,strProgramCode,strNa ...

When trying to create a MongoStore object, an error occurred because the property 'create' was not defined

I have exhausted all possible solutions I could find, but the issue remains unresolved. The error message is as follows: C:\Users\...............\server.js:35 store: MongoStore.create({ ^ TypeError: Cannot read property &a ...

Discovering the initial vacant row within an HTML table with Javascript

Below is a snippet of code that generates a table with 6 rows. The last two rows remain empty. The JavaScript logic in the code correctly determines and displays the total number of rows in the table. I'm currently looking for a way to identify the ...

Changes in React BrowserRouter URLs are not reflected on the page or components, requiring a manual refresh for them to

Greetings, fellow developers! I have developed an app using React with a remote menu component. Despite trying numerous techniques, I am facing an issue where my URL changes but the components are not rendering on the screen. You can check out the code h ...

The functionality of Jquery events is limited when it comes to interacting with HTML elements that

<li> <label>Book Title</label> <input type="text" name="book[1][title]" /> </li> <li> <label>Content</label> <textarea name="book[1][content]" ></textarea ...

What is the best way to manage HTML code that is delivered through JSON data?

I am dealing with data from a JSON that is in HTML code format. I need to print it as HTML, but currently it is only printing as a string: "content": "More tests\u003cbr /\u003e\n\u003cbr /\u003e\n\u003cdiv class=&bso ...

The left-floated image extends beyond the boundaries of the div

I have a situation where text and an image are combined but the cat image goes outside of the parent div. Is there a solution to this issue? View the code here <div style="border:1px solid #CCCCCC"> <img style="float: left;" src="http://plac ...

"Utilizing jQuery's AJAX POST method with PHP is successful, while using XMLHttpRequest is not yielding

Currently in the process of revamping my existing code to transition from jQuery's AJAX function to using XMLHttpRequest in vanilla JS. My understanding is that the following code snippets should be equivalent. However, while the jQuery version functi ...

Creating a unique custom icon by leveraging the material UI icons - a step-by-step guide

I am looking to create an arrow graphic similar to the one shown in the image below https://i.stack.imgur.com/k9TvH.png Originally, I was able to achieve this using SVG - <svg height='24' width='12' style={{ marginBottom: '-4p ...

Enhanced Organic Draping/Drifting

Currently working on creating a basic thumbnail gallery where clicking on a thumbnail expands it to one of three sizes (square, vertical, or horizontal). However, facing the issue where expanded pictures maintain their original order instead of filling emp ...

Executing a function from index.html that continuously loops without any limits

I'm currently working on creating a function that displays specific HTML content only to users with certain roles. Here are the functions I've set up for this: nodejs/server.js app.get('/api/isadmin', ensureAuthenticated, function (re ...

Expanding CSS styles on hover

When my mouse pointer moves out of the red color box, it still triggers the hover function. However, I only want the hover effect to work within the red color box and hide the menu when it's outside the box. This is the source code from JSfiddle: htt ...

How can I combine these scripts that are not working simultaneously?

I have two scripts on my site that are based on the meta title, and I'm trying to make them work together. I thought changing the function names would be enough, but when I use both scripts, one doesn't work. Why is this happening? Also, should I ...

Height of cells is often overlooked in webkit browsers

When adjusting tbody and thead heights, I noticed that webkit does not behave like other browsers. I've set the height of td. Here is an example of what I am referring to: link The question at hand is - which browser is displaying correctly? And ho ...

Transform a list separated by commas into an unordered list

Seeking a PHP, Jquery, or JavaScript method to convert comma-separated data into an unordered list. For clarification, I have uploaded a CSV file to WordPress where one section of content is separated by commas and I am looking to display it as a list. A ...

Error: Unable to locate module: Could not find '@/styles/globals.scss'

I'm encountering an error message with my import statement for the SCSS file in my _app.tsx. Can someone help me find a solution? I'm working with Next.js and have already exhausted almost every resource available online to fix this issue. ...

When sending a POST request to my server and attempting to retrieve the body content, all properties, including arrays, are automatically cast to strings

It recently dawned on me that when I send a POST request like this: async createProduct(){ let formData = new FormData(); formData.append("name", "test") formData.append("price", 150) formDa ...