Skip to content Skip to sidebar Skip to footer

Active Link Turn Different Color

I'm trying to link those three scripts so that a active link turns to a different color purple. jquery.js contains the downloaded jquery library. I don't know why it is not working

Solution 1:

Have you tried simply this?

.navigation-menulia:active {
    background-color: purple;
    color:#fff;
}

Instead of trying to modify CSS classes with JQuery, why not simply do it all with CSS.

CSS active state is defined as

:active

Not as

.active

(Just in case you were trying to target the state and not intentionally doing it using classes)

Edit:

$(".navigation.menu").click(function(){
    $(".navigation.menu").css("color","#fff");
    $this.css("color","#f0f");
});

This may work for you, apologies if this edit is not completely correct as I am on my phone.

Solution 2:

When a link is clicked your click handler will run to change the class (and thus colour) of the clicked item in the current page, but then the normal page navigation will occur and the specified page will load, overwriting the change that was applied to the previous page.

Rather than using a click handler, you could run some code when the page loads to extract the page name from location.href and then use it as a selector to set the class on the anchor corresponding to the current page.

That is, if you could somehow tell that the current page is bsms.php then you could say $("a['href=bsms.php']).addClass("active");. So how would you do that? Here's one way:

$(document).ready(function() {
  var currentPage = location.href.match(/\/(\w+\.php)/);
  if (currentPage) {
    $("a[href='" + currentPage[1] + "']").addClass("active");
  }
});

This uses a regex that assumes the structure of your URLs is some variation on the following:

www.somedomainname.com/optional/folders/pagename.php?optionalargs=something

and just gets the pagename.php part.

The regular expression matches as follows:

\/         - a forward slash (which has to be escaped in the regex)
(          - beginning of a submatch
\w+        - one or more "word" characters
\.         - a literal .
php        - the literal characters php
)          - end of the submatch

The currentPage variable will be null if there was no match, otherwise it will be an array where the element at index 1 is the page name.

Post a Comment for "Active Link Turn Different Color"