Changing the arrow in jQuery's slideToggle for different div elements is a breeze

Good day, I'm struggling with getting the arrow switch to work correctly for slideToggle. Even though I have three of them, the arrow changes only for the first one - no matter which div I click on. Any suggestions on what I might be missing? Thank you.

Check out the demo here

//jquery

$(document).ready(function(){
  $('.flip').click(function(){
  $(this).next('.panel').slideToggle('fast');
        var src = $('#arrow').attr('src') == "arrow-down.png" ? "arrow-up.png" : "arrow-down.png";
        $('#arrow').attr('src', src);
  });
});

//html

<div id="container">    
    <div class="flip">One   <img id="arrow" src="arrow-down.png" alt="" /></div>

    <div class="panel"> 
        <p>Foo</p>
    </div>
</div>

<div id="container">    
    <div class="flip">Two   <img id="arrow" src="arrow-down.png" alt="" /></div>

    <div class="panel"> 
        <p>Bar</p>
    </div>
</div>

<div id="container">    
    <div class="flip">Xxx   <img id="arrow" src="arrow-down.png" alt="" /></div>

    <div class="panel"> 
        <p>Yyy</p>
    </div>

Answer №1

You were referencing the overall $('#arrow') instead of the specific one within the relevant .flip. I resolved it like this:

$(this).find('#arrow').attr('src', src);

I made updates to your jsFiddle…

http://jsfiddle.net/8y6xb9n5/1/

…however, your code is still a bit disorganized. It's better not to have multiple instances of id="arrow". Rather, utilize classes. Additionally, using a ternary operation to compare src values may be excessive. Instead, consider using classes (.addClass(), .removeClass()) and background-image.

In essence, <img> is ideal for content (such as images) while CSS background is more suitable for interface elements (like icons).

Answer №2

You currently have 3 images all with the same id arrow, and you are updating the src attribute for each of them. A more efficient way to do this is by using the following code:

var src = $(this).children('#arrow').attr('src') == "http://www.tuneup.cz/fileadmin/images/2014/others/arrow-down.png" ? "http://www.tuneup.cz/fileadmin/images/2014/others/arrow-up.png" : "http://www.tuneup.cz/fileadmin/images/2014/others/arrow-down.png";
$(this).children('#arrow').attr('src', src);

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

Enable arrow keys feature in Regular Expressions

Currently, I am implementing alphanumeric validation to ensure that users can only input alphanumeric values and also paste alphanumeric values exclusively. In order to achieve this, I have utilized the following regular expression: function OnlyAlphaNum ...

Using a custom font in a Django project without relying on the Google Fonts API

I've hit a roadblock in my programming journey and I'm seeking help. As a newcomer to both programming and Django, I've been following a helpful tutorial up until part 4. Everything was going well until I stumbled upon a new font online cal ...

Having trouble with the "Corrupted @import" error during grunt build?

As I embark on my journey to create my very first Angular application, I have encountered a roadblock. Using Yeoman and angular-generator, everything seemed to be running smoothly with "grunt serve." However, when I attempted to execute "grunt build," the ...

Ways to ensure a video completely fills the frame

I am experiencing an issue where the video in the main div of my home page does not fully fill the div right away - I have to refresh the page for this to happen. As a result, there is black space on the left and right sides. Interestingly enough, this pr ...

Utilizing Highchart for JSON Data Processing

I'm currently working on creating a simple bar chart using JSON data. Here's what I've attempted so far without utilizing the JSON data (http://jsfiddle.net/6hkcn4qf/2/). To achieve the same bar chart, I need to utilize this sample JSON htt ...

The background color feature of a div is malfunctioning

I have encountered a strange issue with one of my Div elements. When I add text inside the div, the background color sticks to the text. However, if there is no text present, the background color disappears. Image with Text: https://i.stack.imgur.com/oYK ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

How to adjust the background picture opacity in HTML

Is it possible to adjust the transparency of a background image in HTML? I came across one solution that involved adding a box on top of the background picture and changing the opacity of the box, which in turn changed the opacity of the background pictur ...

Can a webpage be redirected to another page after an animation using only HTML and CSS?

My goal is to design a landing page that has a button allowing users to trigger an animation before being redirected to another page. This concept involves adding a captivating element before transitioning between pages, similar to a link with a dynamic ...

What is the method to determine the size of a file in Node.js?

Have you ever wondered how to accurately determine the size of a file uploaded by a user? Well, I have an app that can do just that. The code for this innovative tool is provided below: Here is the snippet from server.js: var express = require('expr ...

Loop through each item in the JSON object

After making an ajax call, I receive a json object in the success callback with the following structure: {test 1: Array(2), test 2: Array(3), test 3: Array(2)} The arrays inside each key have elements that look like this: 0: {IdProduct: "1", ProductName ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

Experience the ultimate entertainment with Flowplayer by watching multiple videos simultaneously in two separate views

I have two separate players in two different views within the DOM. Each player retrieves a video file asynchronously from my database using a unique ID. The first player functions correctly, but I am uncertain how to replicate this for ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

What are the elevated sections in bootstrap?

Having come from Semantic-UI and starting to learn Bootstrap, I must say that despite its widespread popularity, I find Bootstrap a bit lacking compared to what Semantic-UI has to offer in terms of basic stylings. Currently, I am on the lookout for the Bo ...

Is there a way to apply border-radius to the header of a table in Bootstrap 5?

My use of Bootstrap 5 for styling a table has encountered an issue. Even with the border-radius set on the table-dark class, the thead element's border does not change. I am looking for a way to address this problem. Any suggestions? .table-dark { ...

Setting maximum and minimum zoom limits for an element ID using JavaScript or jQuery

My application features a DIV element with the unique identifier of mainDiv. The issue I am facing is related to zooming functionality, as it currently lacks any set limits - both for scaling up and scaling down. I have been searching on Google for a sol ...

Utilizing jQuery and PHP to Refine Database Search Results

I am a novice currently embarking on my journey to create my first website, integrated with a database system which is also new territory for me. Struggling to decide between jQuery and PHP for a specific task related to data handling, I seek guidance from ...

Extract ID for Bootstrap modal display

In my project, I am using a bootstrap modal that displays various strings. The challenge I am facing involves a loop of cards, each with a distinct 'id'. When triggering the modal, I want to show the corresponding id inside the modal itself, whic ...

I am looking to showcase images beside individuals' names or photos on my website in a vertical arrangement, similar to how it is done on Facebook

Looking for suggestions on how to display images uploaded by users on my webpage in a way similar to Facebook, with the user's photo displayed beside each image. Any recommendations or website links would be greatly appreciated. Thanks, Santosh Sahu ...