0

I have created list of anchors.On clicking the link,I want to add CSS Class(using addClass) to the link I have clicked upon.

<ul id = "menu">
        <li id="mnuLectures" runat="server">
            <asp:HyperLink NavigateUrl = "~/Lectures.aspx" Text="Lectures" runat = "server" ID= "hypLectures" />
        </li>
        <li id="mnuBooks" runat="server">
            <asp:HyperLink NavigateUrl = "~/Books.aspx" Text="Books" runat = "server" ID= "hypBooks" />
        </li>
        <li id="mnuArticles" runat="server">
            <asp:HyperLink NavigateUrl = "~/Articles.aspx" Text="Articles" runat = "server" ID= "hypArticles" />
        </li>
        <li id="mnuQA" runat="server">
            <asp:HyperLink NavigateUrl = "~/QuestionAnswers.aspx" Text="Q & A" runat = "server" ID= "hypQA" />
        </li>
    </ul>

and JQuery,

$(document).ready(function () {
    $('#menu li a').click(function () {

        $(this).addClass('highlight');

    });
});

The jquery code is not working properly.I am not able to add CSS class to clicked anchor.. Am I missing something or the approach is wrong..Please suggest

5
  • Does clicking the link re-load the page, or is that prevented somehow? Commented May 25, 2014 at 17:16
  • Yes,on clicking the link it loads the new page. Commented May 25, 2014 at 17:21
  • Then your JavaScript won't run, because the browser loads a new page. Commented May 25, 2014 at 17:21
  • if so, you have to modify your HTML code using server-side scripting (to add the current class to the clicked element). Commented May 25, 2014 at 17:22
  • I am using this list of anchors in User Control(used as header).This user control is used in Master page.After clicking the link the browser is hitting the breakpoint at .click().Does it requires Server side handlers.. Commented May 25, 2014 at 17:30

2 Answers 2

1

you have to remove from the first selected as well before applying to the clikced one:

$(document).ready(function () {

    $('#menu li a').click(function (event) {

        $('#menu li a').removeClass('highlight');
        $(this).addClass('highlight');

        event.preventDefault(); // stop default event to stop reloading of page

    });

});
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add event.preventDefault() to the click event. Try this:

http://jsfiddle.net/xec4a/

$('#menu li a').click(function (e) {
    e.preventDefault();    
    $(this).addClass('highlight');
    alert('class added');
});

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.