Jquery script to update the background of the parent element when Bootstrap Tabs

Currently, I am exploring ways to come up with a more sophisticated solution. However, my proficiency in jquery is somewhat limited at the moment.

I believe there must be a more efficient method to achieve the desired function outlined below. In essence, I am attempting to alter the background of the parent element upon clicking.

As it stands now, I simply add a class and remove any other potential classes from the other buttons.

Relevant HTML:

<div class="panel panel-widget widget-latest-posts">
                <div class="panel-heading">
                    <h3 class="widget-title">Also worth reading</h3>
                </div>

                <div class="panel-body">
                    <div class="btn-pref btn-group btn-group-justified btn-group" role="group" aria-label="...">
                            <div class="btn-group" role="group">
                                <button type="button" id="btn-popular-posts" class="btn btn-popular-posts" href="#tab1" data-toggle="tab"><i class="fa fa-fire"></i>
                                    <span class="hidden-xs">Popular</span>
                                </button>
                            </div>
                            <div class="btn-group" role="group">
                                <button type="button" id="btn-latest-posts" class="btn btn-latest-posts" href="#tab2" data-toggle="tab"><i class="fa fa-clock-o"></i>
                                    <span class="hidden-xs">New</span>
                                </button>
                            </div>
                            <div class="btn-group" role="group">
                                <button type="button" id="btn-popular-comments" class="btn btn-popular-comments" href="#tab3" data-toggle="tab"><i class="fa fa-commenting-o"></i>
                                    <span class="hidden-xs">Active</span>
                                </button>
                            </div>
                        </div>

Relevant CSS:

.bpp-toggled {
    background: orange !important;
}
.blp-toggled {
    background: lime !important;
}
.bpc-toggled {
    background: purple !important;
}

Jquery

$("#btn-popular-posts").click(function() {

    $('.widget-latest-posts').addClass('bpp-toggled');
    $('.widget-latest-posts').removeClass('blp-toggled');
    $('.widget-latest-posts').removeClass('bpc-toggled');
});

$("#btn-latest-posts").click(function() {

    $('.widget-latest-posts').addClass('blp-toggled');
    $('.widget-latest-posts').removeClass('bpp-toggled');
    $('.widget-latest-posts').removeClass('bpc-toggled');
});

$("#btn-popular-comments").click(function() {

    $('.widget-latest-posts').addClass('bpc-toggled');
    $('.widget-latest-posts').removeClass('blp-toggled');
    $('.widget-latest-posts').removeClass('bpp-toggled');
});

If you can suggest a better and more elegant solution or perhaps provide keywords for further research, I would greatly appreciate it. Currently, maintaining this code will become increasingly difficult as I add more buttons.

Thank you for your assistance!

Edit: I have tried using toggleClass, but it did not work as expected in this scenario. It simply removed the class on the second click.

Answer №1

This code snippet utilizes data attributes to store the class within the button itself. To remove the current toggled class before applying a new one, a function with a regular expression is employed in the removeClass method.

When adding new buttons in the future, it is essential to ensure that each button contains the appropriate data-target-class attribute and that the correct class is specified in the CSS. As long as consistent naming conventions are followed, no modifications to the JavaScript should be required.

$("button[data-toggle='tab']").click(function() {
    $('.widget-latest-posts').removeClass(function (index, className) {
      return (className.match (/([a-z]{3,3})-toggled/g) || []).join(' ');
    }
  );
  $('.widget-latest-posts').addClass($(this).attr("data-toggled-class"));
});
.bpp-toggled {
    background: orange !important;
}
.blp-toggled {
    background: lime !important;
}
.bpc-toggled {
    background: purple !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-widget widget-latest-posts">
<div class="panel-heading">
<h3 class="widget-title">Also Worth Reading</h3>
</div>

<div class="panel-body">
<div class="btn-pref btn-group btn-group-justified btn-group" role="group" aria-label="...">
    <div class="btn-group" role="group">
        <button type="button" id="btn-popular-posts" class="btn btn-popular-posts" href="#tab1" data-toggle="tab" data-toggled-class="bpp-toggled"><i class="fa fa-fire"></i>
            <span class="hidden-xs">Popular</span>
        </button>
    </div>
    <div class="btn-group" role="group">
        <button type="button" id="btn-latest-posts" class="btn btn-latest-posts" href="#tab2" data-toggle="tab" data-toggled-class="blp-toggled"><i class="fa fa-clock-o"></i>
            <span class="hidden-xs">New</span>
        </button>
    </div>
    <div class="btn-group" role="group">
        <button type="button" id="btn-popular-comments" class="btn btn-popular-comments" href="#tab3" data-toggle="tab" data-toggled-class="bpc-toggled"><i class="fa fa-commenting-o"></i>
            <span class="hidden-xs">Active</span>
        </button>
    </div>
</div>

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

What steps can be taken to design a unique CSS pop-up that triggers upon page load, limited to one appearance per visitor every week

I have the following code snippet that allows me to display a pop-up either by clicking on the link or hovering over it. I am looking to modify it so that the pop-up opens when the page loads and restrict it to open only once per visitor per week. As some ...

Adding a jPlayer on the fly

I've been working on a code snippet to dynamically add jPlayers through a function. Here is the code I have so far: function audio_player(audio, title, type) { var id = $('.audio').length; $('#audio').append('<di ...

"Although disabled, input elements can still be focused on in Firefox browser

Illustrative example let userInput = document.createElement("input"); userInput.id = "user-input"; userInput.type = "number"; userInput.className = "user-number-input"; userInput.disabled = true; document.body.appendChild(userInput); .number-inp ...

The gap between columns in Bootstrap grids

Currently, I am dynamically fetching "boxes" and adding them to the HTML document using ngFor. The number of boxes is unknown in advance. Here is the code I am currently using: <div *ngIf="items && items.length" class="row"&g ...

How can you center a webpage and make it occupy 60% of the screen?

I was attempting to design a website where the main content takes up 60% of the body. This is what I tried initially: body { align-items: center; text-align: left; justify-content: center; width: 60%; } Unfortunately, this approach did not work ...

Updating the Animation for Datepicker Closure

While using the date picker, I want it to match the width of the input text box. When closing the date picker, I prefer a smooth and single motion. However, after selecting a from and to date, the datepicker no longer closes smoothly. I have attempted sol ...

jQuery enables the toggling of child elements with a specific class (handlers) upon clicking

My goal is to change the style of a specific child element when I click on its parent. I was able to achieve this using event handlers: $(".p1").on({ mouseenter: mouseEnter, mouseleave: mouseLeave }); function mouseEnter() { $(this).css(&apos ...

Eliminating clutter in bespoke event handlers - eliminating the necessity for the 'event' parameter

I have a project where I am creating objects that will trigger custom events, and I am using jQuery's bind and trigger functions to handle this task. Here is an example of how I am implementing it: function MyObject() { var _this = this; th ...

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

Bootstrap resource failed to load

I successfully connected the most recent version of bootstrap.min.css to my webpage using <link rel="stylesheet" href="assets/css/bootstrap.min.css">. Initially, everything was running smoothly. However, I now encountered an issue where my browser is ...

What is the best way to create a function that automatically resumes audio playback 3 seconds after the pause button is clicked?

I am looking to develop a basic webpage with an autoplay audio feature. The page would include a "pause" and "play" button. I aim to implement a function where clicking the "pause" button would stop the audio, but after 3 seconds, it would automatically re ...

The placement is set to absolute, with a designated height

Here is an example http://jsfiddle.net/HnfCU/ I am using jQuery to toggle the visibility of the .child div. The position of the .child is set to absolute relative to its parent element, .parent. The challenge I am facing is adjusting the height of the .ch ...

Implementing jQuery to Replace PHP echo Statements

I am in the process of loading images (pinpoints) onto a map. When a user clicks on a pinpoint, a corresponding video URL is loaded from a database. To achieve this, I assign IDs to the images based on their index in MySQL using PHP. This allows me to inte ...

Clicking on the submit button in asp.net triggers the removal of the dropdown list items that were dynamically populated using a jQuery ajax request

I am struggling to populate a select box in asp.net using a jQuery ajax call. The value briefly appears when the submit button is clicked, but then disappears after the page refreshes. It seems to work fine with <input type="button">, but I am lookin ...

Automatically trigger a page reload using a jQuery function

Currently facing an issue with jQuery. I created a drop-down menu and would like it to expand when the li tag within the menu is clicked. Even though I am using the jQuery click function successfully, there seems to be a problem where the webpage refreshe ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

Alter information within jQuery AJAX success function

A sample function is provided below: jQuery.ajax({ type: "POST", url: jQuery("#exam_form").attr( 'action' ), data: jQuery("#exam_form").serialize(), success: function(result){ //Add row table.append(result); ...

Is it possible to utilize the .load() method in JQuery to handle form processing?

Seeking guidance on a technical matter here. Despite my efforts to find an answer online, I have yet to come across a solution. The scenario is this: there's an ASPX page labeled form.aspx, containing a form along with the necessary code behind logic ...

The issue of background-attachment: fixed not functioning properly on Safari

Currently, I have the following code implemented on an element that extends 100% of the browser: #section_white { background-attachment:fixed; background-image:url(image_url_here.jpg); background-position:100% 100%; background-repeat:no-repeat no- ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...