0

I need to check the previous page URL a user has visited for a string, then apply an "active" class to an "a" tag on the current page using jQuery.

e.g. if a user's previous page url contains "new-york" and looks like - "www.domain.com/new-york/", then on the current page I want to check for an "a" tag which contains "new-york" in the link, then add a class to this tag. I have about 20 different cities I need to check and add classes too.

Here is what code I have so far...

$("#cities a").each(function () {
    if ($(this).attr("href") == document.referrer) {
        $(this).addClass("active");
    }
});

I know document.referrer is the exact URL, how do I grab/check for a string from document.referrer?

Thanks

2 Answers 2

1

Taking reference from here.

//assuming referer url is http://example.com/prev
function getLocation(href) {
   var l = document.createElement("a");
   l.href = href;
   return l;
}

//get the pathname from the url----
var l = getLocation(document.referrer);
var pathname = l.pathname;//returns "/prev"

$('a').each(function () {
   var current_url = $(this).attr('href');
   if(current_url.indexOf(pathname) !== -1){
      $(this).addClass('visited');
   }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Can be achieve in multiple ways.
1. document.referrer.indexOf("new-york") > -1
2. document.referrer.match(/new-york/)

Above things will work for your case. But remember document.referrer will not have query string params. If in future you have any case for that, then you can save prev page URL in the cookie, local storage or session storage.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.