Toggling classes in JavaScript on a button to expand a div element

I am facing an issue with a website feature where there is an expanding widget area in the topbar above the header. You can check it out at this link:

After clicking the arrow to expand the area, the button changes its direction. However, when I click it again to collapse the area, the arrow does not switch back to its original position.

Despite trying various solutions related to changing classes on StackOverflow, none of them seem to work for me. The thread I referred to is here: Change an element's class with JavaScript

I need help in figuring out how to effectively switch the class from 'expand-arrow' to 'collapse-arrow' using the existing code provided below. Should I consider ditching this code and opting for something simpler or better?

CSS:

.collapse-arrow {
    display: inline-block;
    width: 24px;
    height: 24px;
    background: url('../../../images/collapse-arrow.png');
}

.expand-arrow {
    display: inline-block;
    width: 24px;
    height: 24px;
    margin-top: 5px;
    background: url('../../../images/expand-arrow.png');
}

Javascript

<script language="javascript"><!-- THIS IS THE SLIDING TOP BAR -->
    (function() {
      var open = false;     
      toggle = function() {
        var ele = document.getElementById("toggleText");
        var text = document.getElementById("displayText");
        ele.style.height = (open ? 0 : ele.scrollHeight)+"px";
        document.getElementById("displayText").className = 
        document.getElementById("displayText").className.replace
        ( /(?:^|\s)expand-arrow(?!\S)/g , '' );                     
        open = !open;                   
      }
    })();   
    </script>

HTML:

Button:

<a class="expand-arrow" id="displayText" href="javascript:toggle();"></a>

Answer №1

Simply use the following code snippet:

<script language="javascript">

function toggle(){
    document.getElementById("displayText").classList.toggle('expand-arrow');
}

</script>

Answer №2

Have you attempted:

if (className.includes("class1")){}

I recommend utilizing jQuery's .removeClass('class1'),.addClass('class2') for code that is easier to read and browser-compatible.

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

Navigating to redirected URL within jquery's get() function

When I tried sending a get request to a Google App Script URL in my application using JQuery's get method, everything was working fine. However, out of the blue, that API started redirecting to a different URL in case of an authentication error. As a ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Encountering a problem while attempting to loop through div content upwards in jQuery, specifically when displaying the latest news

Hey there, I'm fairly new to JQuery and I am working on dynamically appending content to a div. I need to continuously scroll the content of that div to the top. After some research, I found a solution that meets my requirements. Here's a snippe ...

Tips for setting up nextjs with typescript to utilize sass and nextjs font styles

I am attempting to configure a Next.js TypeScript app to work with Sass and a font in Next.js. I have been following the steps outlined in this article. Without the font module, styles are working correctly. Below is my next.config.js without the font co ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...

The real-time updates on an Angular 2 website can be seen across multiple devices simultaneously

Just getting started with Angular 2 and ran into an interesting issue. When setting up my website, NPM defaults the server to http://localhost:3000. To test the site on another computer, I tried accessing it using my IP address http://10.x.x.x:3000 and eve ...

Leveraging the power of jQuery with AJAX operations

In my collection of PHP files, I have three named: index page books user Index Page <link href="colorbox.css" type="text/css" rel="stylesheet" media="all" /> <script type="text/javascript" src="jquery-1.8.2.min.js"></script> <scrip ...

``The art of making Wordpress navigation smoother with jQuery Easing

I am looking to incorporate jQuery easing into my Wordpress theme in order to implement some smooth scrolling effects to specific div id's on the page. I have successfully done this using regular HTML, but I am unsure of how to integrate it with Wordp ...

Scope variable changes are not being acknowledged by the directive

Here is a directive I am working with: <span ng-show="{{ save_state == 'saved' }}"> Saved </span> <span ng-show="{{ save_state == 'saving' }}"> Saving </span> <span ng-show="{{ save_state == 'error ...

Discovering the generic type from an optional parameter within a constructor

Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "und ...

Trouble with loading images on hbs/nodejs

I'm currently working on a web application using NodeJs and express-handlebars. However, I am facing an issue with images not displaying correctly on the HTML page that is being rendered using handlebars. Here is the structure of my app: The root fo ...

Generating numerous visual scenes using the identical renderer

I've been working on rendering multiple scenes using a single renderer, but I'm facing some challenges in getting it right. Despite referring to other Stack Overflow answers, I haven't been able to achieve the desired outcome. My approach i ...

Guide to combining an Angular 2 application with a Django application

Currently, I have been working through the Tour of Heroes tutorial. The structure of my Django app can be simplified as shown below: apps/my_app/migrations/ apps/my_app/__init__.py apps/my_app/urls.py apps/my_app/views.py frontend_stuff/js/ javascript ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

Upon receiving AJAX-content, the next iteration of the $.each function will be triggered

This question has been asked on an online forum in the past, but it was around four years ago and there may be a more efficient solution available now. In my code, I have a loop that sometimes requires additional data to be fetched through ajax calls. Af ...

Change the class upon clicking the element

Looking to create a function that toggles classes on elements when specific links are clicked. For example, clicking on link 1 should add the "active" class to the red element, while clicking on link 2 should do the same for the pink element, and so forth. ...

Can you please explain the purpose of the state object in the setSearchParams hook of react-router-dom v6

Can anyone explain the { state: ? } parameter used in the update function of useSearchParams? const [search, setSearch] = useSearchParams(); setSearch( { ...Object.fromEntries(search), transFilters: JSON.stringify(filters), }, { ...

Passing null values as parameters to a method in an MVC controller using JQuery

Problem Description I am encountering an issue with passing the contents of 'p' and 'h3' tags from a button click in my view. These tags are populated from a list of models passed by the controller. The 'AddToCart' method in ...

How can the entire menu be closed in Bootstrap 5 when clicking on a link or outside of the page?

I'm currently utilizing BootStrap 5 for constructing my webpage. Within my page, I have a NavBar Menu containing various links. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Receive axios responses in the exact order as the requests for efficient search functionality

Currently, I am working on integrating a search feature in React Native using axios. For the search functionality, I am incorporating debounce from lodash to control the number of requests being sent. However, there is a concern about receiving responses ...