I have a page with a link to another page with tabs.
<a href="https://example.com/page#span-01">Goal</a>
Here is the HTML
<div id="builder_tabs" class="tab-buttons tab-buttons-left">
<ul class="nav nav-tabs">
<li class="active"><a href="#builder_tabs-0" data-toggle="tab">
<span id="span-00">Span00</span></a></li>
<li><a href="#builder_tabs-1" data-toggle="tab">
<span id="span-01">Span01</span></a></li>
<li><a href="#builder_tabs-2" data-toggle="tab">
<span id="span-02">Span02</span></a></li>
<li><a href="#builder_tabs-3" data-toggle="tab">
<span id="span-03">Span03</span></a></li>
</ul>
<div class="clearboth"></div>
</div>
<div class="tab-content">
<div class="tab-pane fade active in" id="builder_tabs-0"><strong>Tab-0</strong>
<p>Lorem Ipsum text</p>
</div>
<div class="tab-pane fade" id="builder_tabs-1"><strong>Tab-1</strong>
<p>Lorem Ipsum text</p>
</div>
<div class="tab-pane fade" id="builder_tabs-2"><strong>Tab-2</strong>
<p>Lorem Ipsum text</p>
</div>
<div class="tab-pane fade" id="builder_tabs-3"><strong>Tab-3</strong>
<p>Lorem Ipsum text</p>
</div>
</div>
And the JQuery that works.
(function($) {
$(document).ready( function() {
var query = window.location.hash.substring(1);
if ($(query) ) {
$("ul.nav.nav-tabs li").removeClass("active");
$("#"+query).closest("li").addClass("active "+query );
$(".tab-content").addClass(query).show();
$(this).addClass(query).show();
}
});
})(jQuery);
And with the CSS depending on the query. In this example, span-01
.tab-content.span-01, li.active.span-01 a { background-color: powderblue;}
Now that part is working, I also would like to change background color when I stay on the tabs page. With this code the background color of the selected tab is the same on every tab. And this is not the way it should work.
When I click on a tab, my idea is to retrieve the value of the span id ( I mean span-01,02,03 or 04 ) and keep this variable to add it into the tab-content class.
Any tips for doing this?
2
Answers
To achieve the behavior you described, where the background color of the selected tab is different for eachtab,you can modify your jQuery code to capture the span ID when a tab is clicked,and then use that information to set the appropriate background color.
Here’s an updated version of your jQuery code:
with this code it introduces the setTabBackgroundColor function,which removes existing classes based on span IDs and adds the appropriate class based on the provided span ID.The click event for the tabs now calls this function to update the background color when a tab is clicked.Adjust the CSS accordingly for the different span IDs.
Here is a much cleaner version that simplifies some of the logic and makes it more jQuery-like.
Note: Since this snippet cannot access the fragment, I added a logical OR (
||
) to defer to tab "Span02" on the initial load. This can be removed from the code if you are running it on a local server.