0

I have the following HTML structure:

<div>
    <ul id="Category" class="row list-inline">                
        <li>
            <a href="/products/Category/Cars">
                Cars
            </a>
        </li>
        <li>
            <a href="/products/Category/Cars%20Racer">
                Cars MVC
            </a>
        </li>
        <li>
            <a href="/products/Category/Bikes">
                Bikes
            </a>
        </li>
        <li>
            <a href="/products/Category/Rollers">
                Rollers
            </a>
        </li>                
        <li>
            <a href="/products/Category/Scooters">
                Scooters
            </a>
        </li>
    </ul>
</div>

Clicking on the hyperlink navigates to that respective page (postback). I want to change the background color of the link which got clicked.

I have written the following script for the same:

$("#Category li").click(function () {
    $("#Category li > a").each(function () {
        $(this).removeClass("selectedan")
    });
    $(this).addClass("selectedan");
});

But with no effect. What seems to be wrong?

Rvervuurt
  • 8,589
  • 8
  • 39
  • 62
Hitz
  • 1,041
  • 4
  • 12
  • 27

3 Answers3

2

Here's how I'd handle it given the codesnippet you've given us and knowing that your entire page refreshes:

$(document).ready(function() {
  $("#Category li > a").each(function () {
    if ($(this).attr('href') === window.location.pathname.replace(/\/$/, '')) {
      $(this).addClass("selectedan");
    }
  });
});
<div>
    <ul id="Category" class="row list-inline">                
        <li>
            <a href="/products/Category/Cars">
                Cars
            </a>
        </li>
        <li>
            <a href="/products/Category/Cars%20Racer">
                Cars MVC
            </a>
        </li>
        <li>
            <a href="/products/Category/Bikes">
                Bikes
            </a>
        </li>
        <li>
            <a href="/products/Category/Rollers">
                Rollers
            </a>
        </li>                
        <li>
            <a href="/products/Category/Scooters">
                Scooters
            </a>
        </li>
    </ul>
</div>

Can't guarantee the above will work exactly, but you'll want to do the following concepts:

  • On page load, loop over each navigation anchor
  • Check that the pathname matches the href
    • If they match, add the class
    • If they don't, do nothing
chaseadamsio
  • 883
  • 5
  • 11
  • There are two issues I am unable to resolve due to an ending slash. window.location.pathname adds an ending '\' so the two strings never are equal. Second issue is the %20 in Cars%20Racer. – Hitz Aug 03 '15 at 13:42
  • I've updated my solution to fix the pathname, what's the problem with the `%20` in `Cars%20Racer`? – chaseadamsio Aug 03 '15 at 13:45
  • Your jQuery is a lot more compact. Nice! – Rvervuurt Aug 03 '15 at 13:58
  • I'd probably extract the conditional out into a sensibly named function such as `function isCurrentPage(anchorHref) { return anchorHref === window.location.pathname.replace(/\//, '' }` and change the conditional to `if (isCurrentPage($(this).attr('href'))) { ... }` if I were to write it for myself. It's not _super_ intuitive what's happening in the code otherwise. – chaseadamsio Aug 03 '15 at 14:24
  • Your code 'almost' worked. This is what I had to do to make it work if ($(this).attr('href').replace(/\//g, '') === window.location.pathname.replace(/\//g, '')) – Hitz Aug 03 '15 at 15:36
  • 2
    Doh. That's a bad regular expression. Are you familiar with them and what this one is doing? That's totally my bad, the replace should be `/\/$/`, otherwise with your flag it'll replace every `/` which you don't want. :) If you change the `pathname` expression to the `$` regexp and remoove the first replace, it _should_ work just fine. – chaseadamsio Aug 03 '15 at 15:47
  • Yes that worked. By the way you are missing a closing ')' after replace. Please correct your answer if ($(this).attr('href') === window.location.pathname.replace(/\/$/, '')) { – Hitz Aug 03 '15 at 16:22
  • All set. Thanks for catching that. – chaseadamsio Aug 03 '15 at 17:14
-1

Try this

$("#Category li").click(function () {
    $("a .selectedan").removeClass("selectedan");
    $(this).addClass("selectedan");
});
Muhammad Atif
  • 1,050
  • 1
  • 9
  • 21
  • This will work but the `.selectedan` class is applied to the `li` not the `a`, so I think it should be `$(".selectedan").removeClass("selectedan");` – Kez Aug 03 '15 at 12:52
  • Doesn't actually answer the OP's question. There's a thread explaining the page does a refresh, so this answer isn't correct for the question. – chaseadamsio Aug 03 '15 at 13:39
-1

If you want the menu-point to have a background-color after navigating to it, just add a CSS-class called active (or something similar) to the specific menu-point. In CSS you can then set a styling for that a-tag with a active-class.

.active {
    background-color: orange;
}

See the Fiddle, where I added class="active" to the Bikes-link.

Now, as it comes to adding the active class to the menu points, you have two possibilities:

  1. Manually add the class active to every menu point, copy/pasting the menu to every page and having quite a risk on making a mistake
  2. Use the following piece of code:

.

$(function(){
       var url = window.location.pathname, 
       urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash    if present as it could collide with the link in navigation in case    trailing slash wasn't present there
       // now grab every link from the navigation
       $('#category li a').each(function(){
          // and test its normalized href against the url pathname regexp
          if(urlRegExp.test(this.href.replace(/\/$/,''))){
              $(this).addClass('active');
          }
       });    });

Edited from source. It might not work 100% on your project, so you might be able to adapt it so it works.

Community
  • 1
  • 1
Rvervuurt
  • 8,589
  • 8
  • 39
  • 62
  • I tried it but with the page reload there is no effect – Hitz Aug 03 '15 at 13:03
  • Ah like that. Give me two seconds – Rvervuurt Aug 03 '15 at 13:04
  • Unfortunately, that's not how the `:active` pseudo-selector works. "It allows the page to give a feedback that the activation has been detected by the browser." and does not apply to a place based on the active URL. (https://developer.mozilla.org/en-US/docs/Web/CSS/%3Aactive) – chaseadamsio Aug 03 '15 at 13:05
  • @chaseadamsio It works exactly as the OP wrote: When clicked, it gives something a background. However, he wasn't clear it also needed to have the background when the page reloaded, which is why I added some more info to my answer. – Rvervuurt Aug 03 '15 at 13:07
  • That's fair, but leaving your SO answer of 'use `:active`' still isn't a correct answer based on the response the OP gave in the questions to the question. – chaseadamsio Aug 03 '15 at 13:13
  • @chaseadamsio removed it. – Rvervuurt Aug 03 '15 at 13:17
  • Thanks. I might also suggest giving a recommendation of how to add the class rather than just suggesting adding the class. It seems like the OP understood that they needed to add a class to the active anchor and suggesting google doesn't ensure the OP will find the solution you might think is the "best" solution. – chaseadamsio Aug 03 '15 at 13:21
  • 1
    Also done. The answer can probably not get more of a solution than it is now ;) – Rvervuurt Aug 03 '15 at 13:34
  • 1
    Thanks! That's close to how I was approaching it, but since you've got the upvote yours will show before mine does, so I'm glad there's a good solution for when someone less savvy with using SO finds something that works well. Solid work. – chaseadamsio Aug 03 '15 at 13:38