Deleting a CSS class from buttons inside of two button arrays by utilizing two separate functions

Uncertain if the issue lies within the scope, but essentially...

I have a collection of 4 div buttons stored in an array called main_btns. When these buttons are clicked, they toggle between 2 classes to display different background colors.

Similarly, I also have another array named genre_btns containing 12 buttons that switch between 2 other classes with a corresponding change in background color when toggled.

The challenge is to remove the class from one array when switching between buttons in each array. For example, clicking on a button in the genre_btns array should change the background color of that button. However, if you then click on a button in the main_btns array, it should revert the background color of the previously clicked genre_btns button while changing the color of the new main_btns button. In essence, only ONE background color should be displayed when toggling between buttons in each array.

Here is the code snippet:

<!-- array for main_btns -->
<div id="selector">
    <div id="btn-atoz" class="class2" onclick="toggleClassMainBtn(this)">
        ACTS A-Z
    </div>
    <div id="btn-headlining" class="class1" onclick="toggleClassMainBtn(this)">
        HEADLINING
    </div>
    <div id="btn-weekend1" class="class1" onclick="toggleClassMainBtn(this)">
        WEEKEND 1
    </div>
    <div id="btn-weekend2" class="class1" onclick="toggleClassMainBtn(this)">
        WEEKEND 2
    </div>
</div>

<!-- array for genre_btns -->
<div id="genre">
    <div id="btn-alternative" class="class3" onclick="toggleClassGenreBtn(this)">
      ALTERNATIVE
    </div>
    <div id="btn-blues" class="class3" onclick="toggleClassGenreBtn(this)">
      BLUES 
    </div>
    <div id="btn-country" class="class3" onclick="toggleClassGenreBtn(this)">
      COUNTRY
    </div>
    <div id="btn-dance" class="class3" onclick="toggleClassGenreBtn(this)">
      DANCE
    </div>
    <div id="btn-electronic" class="class3" onclick="toggleClassGenreBtn(this)">
      ELECTRONIC
    </div>
    <div id="btn-hip-hop-rap" class="class3" onclick="toggleClassGenreBtn(this)">
      HIP-HOP&#47;RAP
    </div>
    <div id="btn-jazz" class="class3" onclick="toggleClassGenreBtn(this)">
      JAZZ
    </div>
    <div id="btn-metal" class="class3" onclick="toggleClassGenreBtn(this)">
      METAL
    </div>
    <div id="btn-pop" class="class3" onclick="toggleClassGenreBtn(this)">
      POP
    </div>
    <div id="btn-rnb" class="class3" onclick="toggleClassGenreBtn(this)">
      R&amp;B
    </div>
    <div id="btn-reggae" class="class3" onclick="toggleClassGenreBtn(this)">
      REGGAE
    </div>
    <div id="btn-rock" class="class3" onclick="toggleClassGenreBtn(this)">
      ROCK
    </div>
</div>

<!-- css for button backgrounds -->
<style>
.class1 /* button toggles */
{
    background: #cc516d;
}

.class2 /* button toggles */
{
    background: #963B50;
}

.class3 /* button toggles */
{
    background: #cc516d;
}

.class4 /* button toggles */
{
    background: #963B50;
}
</style>


<script>
//toggles for buttons acts A-Z, headlining, weekend 1, weekend 2

function toggleClassMainBtn(x){
    var main_btns = document.getElementById('selector').children;
    for(var i = 0; i < main_btns.length; i++){
        main_btns[i].className = "class1";
    }
    x.className = "class2";
}

//toggles for genre buttons 

function toggleClassGenreBtn(x) {
    var genre_btns = document.getElementById('genre').children;
    for(var i = 0; i < genre_btns.length; i++){
        genre_btns[i].className = "class3";
    }
    x.className = "class4";

}
</script>

Answer №1

Utilized jQuery in the solution.

Check out this Fiddle.

JavaScript code:

function changeClassMainButton(x){
    var mainButtons = document.getElementById('selector').children;
    for(var i = 0; i < mainButtons.length; i++){
        mainButtons[i].className = "style1";
    }
    x.className = "style2";

    $('.style4').removeClass('style4').addClass('style3');
}

// Genre button toggling

function changeClassGenreButton(x) {
    var genreButtons = document.getElementById('genre').children;
    for(var i = 0; i < genreButtons.length; i++){
        genreButtons[i].className = "style3";
    }
    x.className = "style4";
    $('.style2').removeClass('style2').addClass('style1');
}

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

Keep the division visible once the form has been successfully submitted

Initially, I have created 3 divs that are controlled using input type buttons. These buttons serve the purpose of displaying and hiding the hidden divs. Within these divs, there are forms to store data. Currently, my goal is to ensure that the div that was ...

In Javascript, auto-scroll functionality allows for smooth scrolling up and down the page, which can

My website features a button that initiates an auto-scrolling effect on the page's body. The scroll will continue moving up and down indefinitely until I manually try to scroll the page myself. At that point, I want the auto-scrolling to immediately ...

Strategies for preventing the appearance of empty rows associated with unused <tr> elements

I currently have multiple asp.net panel controls that I am displaying using an html table. These panels are initially set to visible = false, but depending on the data retrieved from the database, some of the panels will be made visible. The issue arises w ...

What is the method for adding pages to the ion-nav component in Ionic with Angular?

How can I implement a UINavigationController-like functionality in iOS using an ion-nav element? The example provided here is in Javascript, but I need assistance with implementing it in Angular. Specifically, I'm unsure of how to programmatically add ...

Can you compare the two input values for validation in an HTML and JavaScript form?

I need assistance with comparing two input values, minN and maxN. I want to display an alert if the logic between these two values is not met. Below is the code snippet that I am using: HTML: <table> <tr> <th>Minimum N</t ...

Check the JSON for verification, if not valid then throw an error during the fetch

ExampleObject serves as a representation of the expected output from the API endpoint. let ExampleObject={ "id":"", "name":"", "Body":"" } Is there a way to confirm that the response contai ...

Determine the next element in the array using a foreach loop

In my Wordpress code, I am using a foreach loop to retrieve category names. $i = 0; foreach($catnamea as $legname ) { $i++; echo $legname[$i].'<br>'; } When I access $legname[0], it displays a category name, and increasing the number li ...

What is the best way to begin at a specific index in an array without skipping any elements?

As I continue my journey of learning JS, I have encountered a task that has left me quite perplexed. The objective is to provide an index to start from and also include the items missing in the array while displaying them in an angular format. Here is what ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

retrieve contact information and store it in an array

Cursor c; ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); c=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,ContactsContract.Contacts.D ...

How can one effectively leverage Rails JS templates in their projects?

I'm struggling to understand the proper usage of Rails JS templates. Are they essentially replacing the success callback on an AJAX request? Why separate the JavaScript executed for a successful request from that of other callbacks? My assumption is ...

Combining associative arrays in PHP

I need to merge an associative array in a specific way using PHP. The data is not already merged, so I have to figure out how to do it. Here is the initial array: Array ( [0] => Array ( [name] => Color [value] => ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

Navigating with Angular: How to properly redirect to a 404 error page for nested routes

I have structured my Angular application so that each feature has its own feature-routing.module.ts. These modules are then imported into the main app.module.ts. However, I am facing an issue where the application is not redirecting to /select-fund when th ...

Using jQuery AJAX to send POST requests in CodeIgniter

I've been trying to configure the jQuery Ajax post URL, but it's not functioning as expected. I've searched extensively and found many solutions, but none of them seem to solve my issue. I've set the base URL in var baseurl = "<?php ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

The inversify middleware is executed a single time

I utilize Inversify for object binding in the following manner: container.applyMiddleware(loggerMiddleware); let module = new ContainerModule((bind: interfaces.Bind) => { bind<Logger>(TYPES.Logger).toConstantValue(logger); bind<ILogger ...

JavaScript code to generate diamond-shaped numbers

Greetings everyone! I am facing an issue with my code that is supposed to generate diamond-shaped numbers using javascript. The code involves two javascript functions triggered by a single onclick event, but unfortunately, one of the functions does not see ...

Discovering a particular element within a Python list by searching for a specific word within the element for printing

I have a list with strings that include both names and locations. I want to print out only the strings in the list that contain either a specific name or location. Although I can use the index to print a specific string and check if a string contains a ce ...

An effective method for converting MongoDB's JSON array of UTC dates to local time using Node.js

Using Node.js to query MongoDB and encountering an issue with Date (ISODate) fields. After querying, the Date format returned is as follows: DT : 2014-10-02T02:36:23.354Z The goal is to efficiently convert the DT field from UTC to Local Time ISOString. F ...