Switch the background image of a link within an accordion with a simple click

I'm attempting to create a toggle effect for a background image on a links within an FAQ accordion using javascript.

After referencing this jsfiddle example (http://jsfiddle.net/QwELf/), I was able to get things to function.

You can view my page in action here ()

However, I've encountered an issue when clicking on the toggle links a third time. The background image appears incorrectly and is out of sync with the expected appearance.

In the contracted state, a right arrow '>' should be displayed, and in the expanded state, a downward arrow should appear, but the opposite is happening.

Oddly enough, the jsfiddle example functions properly even on the 3rd or subsequent clicks. Any thoughts on what might be causing the discrepancy with my implementation?

Script

<script type="text/javascript">
  function changeArrow(element){

var arrow = element;

if(arrow.className == 'background_one'){

  arrow.className = 'background_two';

} else {

  arrow.className = 'background_one';

}

}
</script>

CSS

.background_one { text-decoration: none; padding-left: 26px; background: url(http://skmgroupwork.com/suntrust/landingpages/307m/chevright.gif) center left no-repeat;}
.background_two { text-decoration: none; padding-left: 26px; background: url(http://skmgroupwork.com/suntrust/landingpages/307m/chevdown.gif) center left no-repeat;}

HTML

<a class="background_one" data-toggle="collapse" data-target="#demo4"    onClick="changeArrow(this)">If I transfer my balance to a new Access 3 Equity Line, what will my interest rate be?</a>

Answer №1

Make sure to check for the class, rather than just its existence, especially since you have multiple classes. With jQuery, you can utilize methods like .hasClass(), .addClass(), and removeCLass(). Additionally, consider using .toggleClass() for more convenience.

function toggleArrowBackground(element) {
    var $arrow = $(element);
    if ($arrow.hasClass('background_one')) {
        $arrow.removeClass('background_one');
        $arrow.addClass('background_two');
    } else {
        $arrow.removeClass('background_two');
        $arrow.addClass('background_one');
    }
}

Answer №2

It seems like the issue is arising because the className also includes the class collapsed the second time it is clicked.

Upon using IE's debugger, I uncovered the following:

One possible solution could be using contains instead of equals in the following code snippet (not tested, but should function correctly):

function changeArrow(element){
    element.className = (arrow.className.contains('background_one') ? 
                          'background_two' : 
                          'background_one');
}

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

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

Send the DOM element to a processing function within AngularJS

In this code snippet, there is an attempt to pass a table cell (as a DOM object) to a function. However, it seems that the reference of 'this' does not point to the DOM object for the table cell, but rather to '$scope'. Any suggestions ...

Manipulate the DOM elements within the ng-repeat directive

Hello, I am currently new to AngularJS and have just begun learning how to create directives. While working on a sample project, I encountered an issue with accessing DOM elements rendered inside my directive. Some elements were not accessible in the link ...

Enhancing Values Across a Timeframe Using JavaScript

Last time, I asked about my code. Here is what I have currently: var secs = 100; setInterval(function() { var $badge = $('#nhb_01'); $badge.text((parseFloat($badge.text())+0.01).toFixed(2)); }, secs); I want the counter to increase by ...

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

Using Javascript in the Model-View-Controller (MVC) pattern to load images stored as byte

Despite the numerous solutions available on Stack Overflow, I am still unable to get any of them to work... I am faced with the challenge of setting the "src" attribute of an image tag using a byte array obtained from an ajax call to my controller in Java ...

Ways to troubleshoot setTimeout functioning during HTTP requests?

Utilizing Socket IO in my client app, I have implemented a feature to check for unread events. The process involves making a request to the backend, which then sets a 5-second timeout before checking for any new events and sending them back. // client soc ...

Having a strange glitch when creating a discord bot. Any suggestions on how to get it up and running smoothly?

Each time I attempt to launch my Discord bot, an error pops up in PowerShell. C:\Users\alexa\Desktop\WHA Period Bot\index.js:1 c SyntaxError: Invalid or unexpected token at Module._compile (internal/modules/cjs/loader.js:891: ...

Steps to showcase a form on a webpage using a button

My webpage features an HTML table with a table navigation bar that allows users to add items or inventory. However, when the "add item" button is clicked, a form appears below the table instead of on top of it. I want the form to display itself right on to ...

Determining when all textures have successfully loaded in Three.js and ensuring there are no lingering black rectangles

I'm currently developing a web platform that allows users to customize and preview 3D house models. If the user's browser doesn't support WebGL, the server renders the house and sends screenshots to the client. However, if the screenshots ar ...

`Generating dynamic content based on ajax response``

Hey there! I've got a little challenge on my hands. I've set up 3 input boxes that act as table cells (the header). When the input in one of these boxes changes, a script runs. This script triggers a function that pulls data from my database thro ...

Ensure that the content inside the centrally aligned div is also aligned at the

Looking for a way to center a box on a website I'm designing? Instead of aligning it based on existing centering, use the following HTML / CSS code to ensure that the white box is perfectly centered on the page. .loading { position: fixed; z-in ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

Unable to reach 'this' within a nested function

Struggling with a coding issue for hours now and in need of some assistance. The challenge at hand involves creating an object named Rank. Rank is expected to make DB calls in mongodb to retrieve data needed to populate a matrix, followed by executing nes ...

The concept of selective importing within JavaScript

Seeking guidance on configuring conditional imports for a native library that is built for both node and electron. The challenge arises when one project requires the node implementation for testing, while another project needs the electron version. Projec ...

Dynamic image swapping using JSON key in Angular

Trying to display different icons based on a property that contains specific words. If the property includes "Health Care" or "Health Care .....", I want to show one image, otherwise another. I've tried using ng-show but my syntax seems off. Any sugge ...

In Laravel, the text-overflow:ellipsis property fails to function properly when trying to display unescaped data

Encountering an issue with the property text-overflow:ellipsis. The ellipsis at the end of the truncated text is not showing up as expected. To maintain formatting without escaping data in ckeditor, I am using: {!! $treatment->description !!} speci ...

The webpage fails to return to its original position after the script has been executed

My website has a sticky div that stays at the top when scrolling down, but does not return to its original position when scrolling back up. Check out this example function fixDiv() { var $div = $("#navwrap"); if ($(window).scrollTop() > $div.data("top ...

The Discord.js guildMemberUpdate event: Everything you need to know

I am currently working on creating a welcome message bot using Discord.js. The goal is to have the bot send a welcome message through a webhook in a specific channel when a member gains access to it. Here's what I have so far: client.on("guildMe ...

Accessing a Global Variable within a Node Express Class Module

Within my Node Express application, I defined a variable in app.js like so: let accounts = [checkingAccount, savingAccount] Now, I have a class file named account.js (not a route) and I need to access the accounts array from within it. How can I achieve t ...