Jenny
Jenny

Reputation: 919

How to check if href contains variable

I would like to add a class to links that contain the variable "activeLink".

The intention is to highlight the currently active link, which means the link that points to where the user currently is.

Here is what I have tried:

//This gets the url parameter
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var pair;
    for (var i=0; i<vars.length; i++) {
        pair = vars[i].split("=");
        if (pair[0] == variable){
            return pair[1];
        }
    }
    return false;
}

//This is where it is stored in variable activeLink
var activeLink = getQueryVariable("pagename");

//This is where I am having trouble
$('.nav a').each(function(index, element) {
  if($('.nav a').attr("href") == activeLink) {
    $(this).addClass('active');
  }
});

Upvotes: 3

Views: 3242

Answers (3)

Hastig Zusammenstellen
Hastig Zusammenstellen

Reputation: 4450

No need for .each in this case as .find will "search through the descendants of these elements".

Answer based on needing just the filename (and optionally query string but not the full url)

//var url = 'file://yi/er/san/page.php?page=4'; // use this variable for testing
var url = window.location.href;
var filepath = url.lastIndexOf("/") + 1;
var matchThis = url.substr(filepath);
$('.nav').find("a[href*='"+matchThis+"']").addClass('active');

Upvotes: 2

Alen.Toma
Alen.Toma

Reputation: 4870

Your function seems right with smal change

try this

 $(document).ready(function(){
   var activeLink = getQueryVariable("pagename");
   $('.nav a').each(function(index, element) {
      if($(this).attr("href").indexOf(activeLink) != -1)
         $(this).addClass('active');
   });
  });

Upvotes: 0

Chris Riebschlager
Chris Riebschlager

Reputation: 1333

You can use String.prototype.includes() to find if the link contains that string instead of equals that string.

var activeLink = getQueryVariable("pagename");

$('.nav a').each(function(index, element) {
    if($('.nav a').attr("href").includes(activeLink)) {
        $(this).addClass('active');
    }
});

Upvotes: 0

Related Questions