1

I love this bit of Jquery, which adds an active class to a link if the link matches the current page URL. However, for this to work, it requires links to contain the full URL.

$("a[href*='" + location.pathname + "']").addClass("active");

How can I ask it to work with just the file name, i.e. index.html?

I'm not familiar with Jquery. Can anybody point me in the right direction?

Thanks in advance.

Carlos
  • 11
  • 2
  • Try this ```location.pathname.substring(location.pathname.lastIndexOf('/') + 1)``` – Mulli Mar 27 '19 at 01:23
  • Possible duplicate of [Get the page file name from the address bar](https://stackoverflow.com/questions/8497050/get-the-page-file-name-from-the-address-bar) – showdev Mar 27 '19 at 01:58
  • Hi - just following up. Was this question answered satisfactorily? If there is more we can help with, please add a comment below an answer, or edit your question to clarify what else you need help with. Otherwise, it would be great if you could choose a "best answer" (by clicking the checkmark beside the answer) to close out the question. If no answer provided helpful information, please add your own answer and select that as the best answer. You won't get any points for doing so, but that will close out the question. *Thanks!* – cssyphus Apr 03 '19 at 19:42
  • Hi Carlos - following up again. Could we trouble you to close out this question by choosing a correct answer - or providing one yourself? That would be a help to us. *Many Thanks* – cssyphus Jun 12 '19 at 13:11

1 Answers1

0

The jQuery you posted does this:

  1. Find all <a> elements

  2. That have an href attribute

  3. That contains the phrase: whatever is in the address bar

  4. And for each of those that match, add class "active"

Because the jQuery searches for a tags that contain what is in the address bar, you should alright if the address contains a subset of what is in the a tag's href.

There is also the possibility that a leading slash could be a problem. This will remove the first character from the "pathname" - so, for example, if the URL is "/index.html" this will search for "index.html".

$("a[href*='" + window.location.pathname.slice(1) + "']").addClass("active");

If this answer does not help, please post a comment below the answer providing more information (i.e. WHY does this answer not solve the problem - what was missed?) so that other viewers can assist.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • That's a very helpful breakdown of the code, thank you. I didn't want to over simplify, but I'll add an extended post in a few minutes explaining my problem and question further. – Carlos Mar 27 '19 at 14:50
  • Thanks Carlos. You might find better results, though, if you close out this question (select a correct answer (via checkmark), or add your own) and create a new question. You'll get more views that way, more people assisting. – cssyphus Mar 27 '19 at 15:07