0

Iam trying to add active class in the <li> but it's not working.

This is all my codes in the view:

<script type="text/javascript">
    $(document).ready(function () {
        $('#nav li.menu').click(function () {
            $('#nav li.menu').removeClass("active");
            $(this).addClass("active");
        });
    });
</script>

<nav id="nav">
    <ul class="nav nav-pills nav-stacked">
        <li class="main_menu"><span class="fa fa-bars fa-lg icon_here"></span> &nbsp;&nbsp;<span class="main">MENU</span></li>
        @foreach (var item in Model) {
          <li class="menu"><a href="@Url.Action(item.sm_action_name,item.sm_controller)">&nbsp;&nbsp;&nbsp;<i class="fa fa-dot-circle-o fa-lg"></i>&nbsp;&nbsp;&nbsp;@item.sm_name</a></li>
        }
     </ul>
</nav>

This is what displayed in the console:

enter image description here

Josh Crozier
  • 202,159
  • 50
  • 343
  • 273
Jen143
  • 737
  • 12
  • 32
  • 1
    Wrap the JS code in `ready`. Code `$(document).ready(function () { $('#nav li.menu').click(function () { $('#nav li.menu').removeClass("active"); $(this).addClass("active"); }); });` OR **Move the script to the end of body**. For reference http://stackoverflow.com/a/32222881/2025923 and http://stackoverflow.com/a/32558249/2025923 – Tushar Oct 13 '15 at 04:54
  • where is your script placed? – Arun P Johny Oct 13 '15 at 04:56
  • I put my script code on the top – Jen143 Oct 13 '15 at 04:57
  • also whether the link related html is created after the page is loaded – Arun P Johny Oct 13 '15 at 04:57
  • then that is the problem... your script is executed before the dom elements related to the nav is created so none of the click handler is added to the `li` elements... so follow the answer in the first comment – Arun P Johny Oct 13 '15 at 04:58
  • @Jen143 Please add some description, of what's happening, what is not working, any error in console – Tushar Oct 13 '15 at 05:04
  • Have you included jQuery on page? And included it before using it? – Tushar Oct 13 '15 at 05:05
  • Yes, all jquery files are place in the BundleConfig.cs – Jen143 Oct 13 '15 at 05:06
  • where is your Jquery File placed?? put it on the head and also check the might be you calling two jquery files that creates the Confliction Sometimes. – Akhilesh Singh Oct 13 '15 at 05:10
  • @Jen143 Try `$('#nav').on('click', 'li.menu', function () {` to bind event – Tushar Oct 13 '15 at 05:17

0 Answers0