bambi
bambi

Reputation: 1179

Active link not changing color

My navigation links are in layout page and they look like:

<h3 id="my-navigation">
   <a href="@Url.Action("Questions", "Question")">ANKETA</a>
   <a href="@Url.Action("Statistics","Administrator")">STATISTIKA</a>
   ...
</h3>

I need active link to change color. CSS to achieve this:

#my-navigation a.active {
    text-decoration:none;
    color:#E0EBEB;
}

Since there are no navigation links in all html pages, but just in layout, I tried with javascript:

$('#my-navigation a').click(function () {
    $('#my-navigation a').removeClass('active');
    $(this).addClass('active');
});

Why doesn't this work?

EDIT: I realised that this gives effect just temporary (at the time of click). For example:

$(document).ready(function () {
    $('#my-navigation a').click(function () {
        $('#my-navigation a').addClass('active');
    });
});

blinks all links on click. So, what to do?

Upvotes: 0

Views: 129

Answers (2)

Oceanity
Oceanity

Reputation: 194

The jQuery script you've included works just fine on my end, so I'd say the issue is most likely either with the version of jQuery you've linked on your page or the script being loaded before the links fully render.

Try surrounding the script you listed with a document ready like this:

$(document).ready(function() {
    $('#my-navigation a').click(function () {
        $('#my-navigation a').removeClass('active');
        $(this).addClass('active');
    });
});

It is also acceptable to replace the first line with the shorthand version:

$(function() {

This will ensure the page's content is fully loaded before it assigns the on click trigger to the links, as the links must exist prior to that being defined.

Upvotes: 1

Gus Ortiz
Gus Ortiz

Reputation: 662

Your code should work, at least it works here: https://jsfiddle.net/kvk1keds/ I just changed the click method for

$('#my-navigation a').on('click', function (ev) {});

You should make sure that the method is running and the class 'active' is being set.

Upvotes: 0

Related Questions