Switching between images with a simple click in various locations

I'm currently working on implementing an accordion feature where I am using custom arrow icons (pngs) as the toggle buttons. The idea is that when you click on the red down arrow, it changes to a blue up arrow to collapse the section, and vice versa.

Although I managed to make it work with the code below, I encountered an issue when trying to apply the same functionality to multiple accordions using the same arrow icons. Despite modifying the IDs and updating the JavaScript accordingly, only the first accordion seems to toggle properly.

Is there anyone who can assist me in achieving this desired behavior across all sets of images?

HTML:

<img src="/wp-content/uploads/2019/08/accordion-open.png" alt="accordion icon" id="accordion" onclick="change();"></div>

JS:

var image_tracker = 'open';

function change(){
 var image = document.getElementById('accordion');
 if(image_tracker=='open'){
 image.src='/wp-content/uploads/2019/08/accordion-close.png';
 image_tracker='close';
}
else{
 image.src='/wp-content/uploads/2019/08/accordion-open.png';
 image_tracker='open';
}
}

Answer №1

When assigning a listener by ID, keep in mind that it will only affect the first instance. Consider using a class name instead for broader impact.

<html>
<body>
    <img class="accordion_icon" src="/wp-content/uploads/2019/08/accordion-open.png" />
    <script type="text/javascript">
        var open_src = "/wp-content/uploads/2019/08/accordion-open.png";
        var close_src = "/wp-content/uploads/2019/08/accordion-close.png";
        let accordion_icons = document.getElementsByClassName('accordion_icon'); // retrieving all icon img tags
        for (let i = 0; i < accordion_icons.length; i++) {
            const element = accordion_icons[i];
            element.addEventListener('click',(event)=>{ // adding listener to each one
                console.log('Current src: ', event.currentTarget.src);
                event.currentTarget.src = (event.currentTarget.src == open_src ? close_src : open_src) // toggling between image sources
                console.log('Src now: ', event.currentTarget.src);
            });
        }
    </script>
</body>
</html>

Answer №2

If you prefer to maintain the event handler in the HTML, another option is to use this method:

<img src="/wp-content/uploads/2019/08/accordion-open.png" alt="accordion icon" id="accordion" onclick="change(this);"></div>

Here is how you can implement it in JavaScript:

function change(image){
  image.src = image.src.endsWith("open.png")
           ? image.src.replace(/open\.png$/, "close.png")
           : image.src.replace(/close\.png$/, "open.png");
}

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

Error: TypeScript is unable to find the property URL within the specified type. Can you help

Currently, I am honing my skills in TypeScript and encountering a problem. I am a bit confused about how to define the type for the URL when I am setting the mix here. Obviously, the URL is supposed to be a string, and this specific scenario is within the ...

How to use jQuery to target every anchor element within an unordered list

I am trying to manipulate an unordered list structure by changing the class of the anchor tags when a specific link is clicked. For example, when the link in List Item 1 is clicked, I want to change the class of all links underneath List Item 1 to "yes". ...

Utilize the Static Path in Django with Template Filters

To easily version my css file using a simple template variable, I update the version in my settings and it automatically applies to all files. Here's how I accomplish this: Template Filter @register.filter def settings_value(name): return getatt ...

Why do I see my footer displayed twice on the page?

<div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li> @Ajax.ActionLink("Imagenes List", "Images", "Home", new { page = 0 }, new AjaxOptions() ...

An easy guide on implementing the if control statement within a Jinja2 embedded HTML document

Utilizing parsehub, I have successfully scraped a list of movie names and exported it to an html file using a python script. However, my intention is to only display titles that contain the word "The" by implementing an if statement. The code structure app ...

Joomla CSS styling malfunctioning

I've been exploring the creation of an in line menu using Joomla 1.6 and CSS. The issue arises when Joomla removes <span class="dmenu"> from the document before saving, despite having all cleanup options turned off. This led me to try a couple ...

Guide to incorporating Circular Animation within a Div Container

Currently, I am making changes to this jsfiddle. However, the issue I'm facing is that I can't get it to circle around in a specific direction. .dice-wrapper { position: absolute; top: 209px; right: -9px; display: -webkit-box; ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

The utilization of 'ref' with React Styled Components is proving to be ineffective

Using refs in Styled Components has been tricky for me. When I attempt to access them in my class methods as shown below, I encounter the error message: Edit.js:42 Uncaught TypeError: this.....contains is not a function constructor(props) { .... ...

THREE.js distributes particles uniformly across intricate 3D models

I am in search of a method to achieve a similar effect as seen in this . My main focus is on the potential for evenly distributing particles (or vectors) like in the above example, but within a complex model that has been imported from Blender. Is it fea ...

Comparison of Angular.js formsets to Django's formset

Within Django, formsets allow for the use of multiple forms within one larger form. For example, you can add multiple books to a library formset by repeating the same book form with details such as author and title. I am looking to achieve similar functio ...

What is the best way to execute a JavaScript function using Python Selenium?

Is it possible to repeatedly call the MapITRFtoWgs84() function with input from a text file and save the output to another text file? I believe Selenium might be the right tool for this task. Could you provide guidance on how to achieve this? Attached is ...

Jquery Position behaving unexpectedly during initial invocation

My goal is to have the autocomplete menu open above the input box if there is not enough space below it. The code functions properly, except for the initial render. It consistently displays at the bottom in the following scenarios: 1. When starting a searc ...

Centering headings and form elements in Bootstrap

I have a bootstrap row with a heading and an input field. Here is my code: <div class="row mb-5"> <div class="col h1 text-white text-start text-center text-md-start text-lg-start">Welcome<input class="for ...

Change to the camera view after the three js has finished loading

Is there a way to switch to a camera once an object with a perspective camera is loaded? I have an avatar object that contains a perspective camera and I want to use it either directly upon loading or switch to it afterwards. I've tried using orbit co ...

JavaScript code to store all the dates of the week in an array

In my quest to gather all dates within a given range in JavaScript, I have the start date and end date of the week at my disposal. My goal is to compile an array containing all the dates that fall within that particular week. For instance, if my week ran ...

Tips for choosing a frequently utilized CSS class inside a specific div element

How can I target the .formlabel class within formblock2 in my CSS code to change the color of Heading B to green instead of red? .formblock2 .formlabel {color:green;} <div class="form"> <div class="formblock1> <div class="formlabel"> ...

What is the method for reversing the colors on a specific portion of an element?

Picture this scenario: you have a square shaped div with the following styling: div { background: red; height: 5rem; width: 5rem; } How would you modify its styling so that the color of the bottom half of the red square is inverted? ...

What is the best way to position one element on the far left and the other element on the far right within the same container?

I am facing an issue with aligning text and icons in a container. I want the text to align far left, and the icons to align far right. Also, the icons should be horizontally oriented according to the length of the text. I have already separated the text an ...

Implementing dynamic ID routes in React Router using JSON data

As a beginner in React, I have been working hard to improve my skills every day. However, I am currently facing a challenge with creating dynamic routes using JSON characters (specifically from Dragon Ball Z). Although my routes are set up correctly, I wo ...