Avatar of coolispaul
coolispaulFlag for United States of America

asked on 

styling tab when clicked

Hi,

Is there an easy way to style a navigation tab when it has been clicked.
What i want to do is style a tab when a user is on the approriate page. i.e if they are on the homepage then the background of the tab is blue.

I know this can be done using server side language, by finding out the page and applying a css class.

However, can this be done using just css? or using javascript aswell?

thanks
PHPJavaScriptCSS

Avatar of undefined
Last Comment
German_Rumm
ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of German_Rumm
German_Rumm

Yeah, you can do it with a javascript, although I would use server-side solution.

Example:
<!-- STYLE -->
.tabs .current {
  background-color: blue;
}

<!-- Your tabs -->
<div class="tabs">
<a href="test.html">Test.html</a>
<a href="test2.html">Test2.html</a>
</div>
<script type="text/javascript">
  function highlight_tab() {
    var links = document.getElementsByTagName('a');
    for (i = 0; i < links.length; i++) {
      var href = links[i].href;
      if (window.location.href.match(href) != null) {
        links[i].className += " current";
      }
    }
  }

  window.onload = highlight_tab;
</script>

How it works:

It goes through all the links on the page. Checks their href attribute against current location and if location contains it, applies "current" class to the matching link.

That's basic version of the script, it will not work with relative urls, and probably contains some bugs that will cause hightlighting wrong <a> elements, or maybe highlighting more than one.
JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo