Switching images with Jquery

Seeking help to create an FAQ page using HTML, CSS, and jQuery. My goal is to rotate an arrow when a question is opened and revert it back when another question is clicked. I've successfully achieved this with <p> tags but facing issues with the image rotation. Does anyone have insight on how to accomplish this?

Here's the code I've written: http://jsfiddle.net/jmex1p5g/62/

   $(document).ready(function(){
  var $li_p = $('ul[class="questions"] li').children('p');
  var $li_a = $('ul[class="questions"] li').children('a');
  if($li_p.slideToggle().toggleClass('closed')){
    $li_p.hide();
  }
    $('ul[class="questions"] li').click(function() {
       var ullist = $(this).children('p:first');
       ullist.slideToggle().toggleClass('closed');

        var isVisible = ullist.is(".closed");
        var siblings = $(this).siblings('li');
        $.each(siblings, function (i, key) {
          if ($(key).find('a').hasClass('icon_minus')) {         
              var sibling = $(key).children('p:first');
              $(sibling).slideToggle().addClass('closed');
            $(key).find('a').removeClass('icon_minus').addClass('icon_plus');
          }
        });


      var img_icon = $(this).children('a');
      var image = $(this).children('span');

      var realimage = $(image).children('img');
      if (isVisible === true){
            img_icon.removeClass('icon_minus').addClass('icon_plus');
            realimage.removeClass('rotate');
            $(this).siblings('img').removeClass('rotate');
      } else {
            img_icon.removeClass('icon_plus').addClass('icon_minus');
            realimage.addClass('rotate');
      }
    });
  }); 

Answer №1

I made some changes to your fiddle: http://jsfiddle.net/jmex1p5g/63/

The key adjustment is to first remove the rotate class from all images before applying it to the selected image. This is a standard practice.

Here is the updated code snippet:

$('ul[class="questions"] li').click(function() {
   // ...
   // relevant code
   // ...

  var img_icon = $(this).children('a');
  var image = $(this).children('span');

  var realimage = $(image).children('img');
  if (isVisible === true){
        img_icon.removeClass('icon_minus').addClass('icon_plus');
        $('li.question img').removeClass('rotate');
        realimage.toggleClass('rotate');
  } else {
        img_icon.removeClass('icon_plus').addClass('icon_minus');
        $('li.question img').removeClass('rotate');
        realimage.toggleClass('rotate');
  }
});

  //... 
  //additional code goes here

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

What is the reason behind H1 tags not requiring a class or ID in CSS?

As I was reviewing my CSS code, I noticed that the h1 tag is defined like this: h1 { .... } Unlike everything else in my code, which either has an id "#" or a "." class preceding it. This made me wonder why header tags don't require this. Could it b ...

Utilizing Data Binding in D3.js

Why is the text "Hello" not appearing five times on the page as expected? index.html <html> <head> <title>Data Binding</title> </head> <body> <h1>D3.js</h1> <script src="https://d3js.o ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

Guide to implementing an ES6 template within an HTML anchor tag href

Hello there, this is my first time seeking assistance here. I have an ajax request returning a JSON response. Now, I am aiming to use the response data to dynamically generate recipe titles and also create clickable links with that data. $( window ).load( ...

The beginning of my HTML input is not at the top of the page

I have a query regarding the custom input line I created recently. When I adjust the height of the input, instead of aligning with the top, the text appears vertically centered. Moreover, the text does not wrap to a new line once it reaches the outermost ...

The enhancement of clickable link padding

I'm having an issue with the padding around the link in my dropdown menu not being clickable. The text itself works fine when I hover over it, but the surrounding padding is inactive. I tried styling it as an inline-block as suggested, but that did no ...

Expandable menu featuring visual icons and a toggle symbol

I am in need of assistance to implement an accordion menu with unique picture icons for each item on the left and a toggle icon (such as + or a chevron) on the right side. Visually, I would like it to resemble this design (https://codepen.io/kathykato/pen ...

Fancybox is showcasing all of the gallery images

I am encountering an issue with FancyBox 2 where, upon clicking the link to open the slideshow, all images are displayed at once. In some cases, it even adds a scroll bar. Please refer to the code snippet below: http://jsfiddle.net/Tx3AF/ Unfortunately, ...

When an external image is dragged over, include the class in the drop area of the file input

Hey, does anyone know how to use Jquery to add a class when an element is being dragged over a drop area? Here's the HTML code I'm working with: <div class="upload"> <form action=""> <input class="uploadfile" type="file" ...

Is there a more efficient way to consolidate multiple functions like this into one cohesive function instead of having to define each one separately?

After attempting to implement a loop without success, I also considered using regex but that did not work either. The code in question is part of a larger project that involves dynamically adding and deleting fields using jQuery. The classes and ids used f ...

Display a PDF document within a div using jQuery or AngularJS

How can I display a pdf file inside a div using jQuery/AngularJs? For example: $.get('/helper/test.pdf', function(data){ $("#div1").html(data); // want to show the pdf in this div }); Or with AngularJs: $http({ meth ...

Leveraging BeautifulSoup for extracting information from HTML documents

I'm working on a project to calculate the distance between Voyager 1 and Earth. NASA has detailed information available on their website at this link: ... I've been struggling to access the data within the specified div element. Here's the c ...

What steps can you take to stop a tab from being inserted if one is already present?

I am facing a simple issue where I need to prevent the insertion of a tab if one already exists. Issue: I have a search bar that displays results in a div with class.result_container_2 when a user inputs a name. Upon clicking on this tab, another tab is i ...

How can jQuery Validate show validation messages specific to each field?

I need to validate numerous mandatory fields and display alert messages in a specific format: "Please fill in" followed by the field label. Currently, I am manually implementing this validation method as shown below: $("#myform").validate({ rules: { ...

Is it feasible to arrange <DIV>s based on their dates?

I encountered an issue while working with an ordering function. var $wrapper = $('#list'); $wrapper.find('.blogboxes').sort(function (a, b) { return +b.dataset.date - +a.dataset.date; }) .appendTo( $wrapper ); <script src="ht ...

Exploring the wonders of multer in a nodejs application

I am having trouble uploading a file from my webpage to a Node server. Although I can see that the form data is reaching the server's router, No file seems to be saved in the upload folder. What could I be doing wrong? //router section const expr ...

The criteria set by jQuery are met

I have developed my own custom form validation for two inputs: one for a phone number and the other for an email address. Additionally, I have integrated two forms on a single page. Here is a snippet of my code: var email, phone; if (email address passe ...

Optimize your Number Selector to the maximum capacity

I am in search of a way to implement a max option on my function. I am contemplating whether using data attributes on the input is the best approach, but I have a feeling there might be a more straightforward solution in jQuery. It's important to note ...

Using JQuery Ajax in Internet Explorer will only execute a single time

I've encountered an issue with my code where I have set cache to false, but in Internet Explorer it only runs once. Can someone please assist me with this problem? <script type="text/javascript" src="javascripts/jq1.7.js"></script> <sc ...

Preventing scrollbar-induced content shifting in Material-UI components: A guide

My browser app displays content dynamically, which can vary in length compared to the screen size. This causes a vertical scrollbar to appear and disappear on desktop browsers, leading to the content shifting left and right. To prevent this, I apply style ...