0

I have a menu including the following li

<div class="menu">
    <ul>
       <li><a href="index.jsp" class="active">Home</a></li>
       <li><a href="listnews.jsp">News</a></li>
       <li><a href="abc.jsp">ABC</li>
    </ul>
</div>

In this code, home page is actived. But want to enable active status when I click on my News page. How Can I do? Thanks for watching.

leebongee
  • 103
  • 1
  • 10

7 Answers7

2

Please add Js like:

jQuery(document).ready(function () {
  jQuery('.menu li a').click(function () {
      //removing the previous selected menu state
      jQuery('.menu li').find('a.active').removeClass('active');
      //adding the state for this parent menu
      jQuery(this).addClass('active');

  });
});
a.active {
 color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
    <ul>
       <li><a href="index.jsp" class="active">Home</a></li>
       <li><a href="listnews.jsp">News</a></li>
       <li><a href="abc.jsp">ABC</li>
    </ul>
</div>
Joykal Infotech
  • 1,840
  • 3
  • 9
  • 17
2

You can use jQuery to do so, use the script below:

$(document).ready(function () {
  $('.menu ul li a').click(function () {
     // This will remove active class from other links
    $('.menu ul li').find('a.active').removeClass('active');    
    // This will add active class to the link clicked 
      $(this).addClass('active');
   });
});
Ifrah
  • 143
  • 1
  • 6
  • @JoykalInfotech I have added the code I use for the condition like this, this may be same but surely not copied. – Ifrah Apr 10 '19 at 10:07
2

Here is code using pure javascript

화이팅!!

function change(elem){
  var list = document.querySelectorAll(".menu ul li a");

  for (var i = 0; i < list.length; ++i) {
    list[i].classList.remove('active');
  }
  elem.classList.add('active');
}
.active{
color:red;
}
<div class="menu">
    <ul>
       <li><a href="#" class="active" onclick="change(this)">Home</a></li>
       <li><a href="#" onclick="change(this)">News</a></li>
       <li><a href="#" onclick="change(this)">ABC</a></li>
    </ul>
</div>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
  • 1
    정말 고맙습니다. Thanks. – leebongee Apr 10 '19 at 09:42
  • I'd thought that you're Korean, but not. I'm sorry. I'm Vietnamese. Nice to meet you :) – leebongee Apr 10 '19 at 09:57
  • I am woman from israel that know korean (learn by myself :) ) – לבני מלכה Apr 10 '19 at 09:59
  • 1
    I like Korean too, if you've free time, let's talk about Korea. It's my pleasure to talk with you. – leebongee Apr 10 '19 at 10:03
  • You shouldn't use "var" anymore. "let" works here. Except in weird circumstances, let is more secure and will work better (and sometimes faster). However, if you have something like this `var x=0; var x=1;` that will work with _var_ but not let. Also "const" is available now too, so use that for unchanging data (constants). It has good browser support (not IE 11 though, but as Microsoft is discontinuing IE, it shouldn't be an issue). – Fighter178 Dec 07 '22 at 00:48
  • I would like to add, that the "this" parameter is not a11y. Okay for most things, but not for screen readers and accessibility tools, as they won't know what "this" is. I give you the upvote anyway, as it is pure JS. Though I tried it in a Svelte project and it doesn't work, I did adapt it to use events though, passing an event instead of the element itself, and modifying the function a bit. – Fighter178 Dec 07 '22 at 00:50
1

With some JS or JQuery , Add a click event on your links and call a method


<div class="menu">
    <ul>
       <li><a href="index.jsp" click="MyMethod">Home</a></li>
       <li><a href="listnews.jsp" click="MyMethod">News</a></li>
       <li><a href="abc.jsp" click="MyMethod">ABC</li>
    </ul>
</div>

and in Jquery(or JS) : perform this :


YourLinkClicked.removeClass('active');
YourLinkClicked.addClass('active');

Or just look at this link : http://jsfiddle.net/designaroni/E53t9/

Eros Guil
  • 31
  • 10
  • This is jQuery, if you wish to add a class with Javascript you should use `classList` - [read more link](https://www.w3schools.com/jsref/prop_element_classlist.asp) – Marc Hjorth Apr 10 '19 at 08:09
0

Modifying @לבני מלכה's answer to

a) Be a11y

b) Work with frameworks (like svelte)

c) Use events instead of the element itself (better for accessibility).

d) Have JSDoc Comments (for whoever must revise my code when this is old and non-modern).

Here is the HTML markup (pure HTML) :

<div class="navbar">
  <ul>
    <li><a onclick="change(e)" class="active">Link 1</a></li>
    <li><a onclick="change(e)">Link 2</a></li>
  </ul>
</div>

Pure JS (w/ JSDoc):

/**
    * This function is used in the navbar. It gives styles to the active link. 
   * @param {Event | Undefined} e Event (click event).  
*/
const change = (e) => {
        if (!e) e = window.event; // <-- for Chrome <89, Firefox (I forgot versions), and Safari. 
        // If you have been used to JS for a bit, you may think that {} needs to be used above, but no. In modern JS, this is unnecessary. Of course, for multi-line if statements, you do need the brackets. 
        let list = document.querySelectorAll(".navbar ul li a");

        list.forEach(elem => {
            elem.classList.remove("active");
        });
        // Note the below comment is only if you are using a type checker, if you aren't then you can remove this. (the comment).
        // @ts-ignore
        e.target.classList.add('active');
    }
Fighter178
  • 303
  • 2
  • 9
0

The best and easy way to do it:

  1. Just listen event on parent of list (ul)
  2. After click find old active element and remove class for it
  3. Set active class for target of event

document.querySelector('ul').addEventListener('click', event => {
  // remove old active
  document.querySelector('.menu .active').classList.remove('active');
  // set new active
  event.target.classList.add('active');
})
a {
  color: #ccc;
  text-decoration: none;
}

.active {
  color: blue;
}
<div class="menu">
    <ul>
       <li><a class="active">Home</a></li>
       <li><a>News</a></li>
       <li><a>ABC</a></li>
    </ul>
</div>
gureenkov56
  • 172
  • 3
-1

Here is some basic function i use for my current MVC project.

Add this to the master page or shared pages, the js need to run each time the site reload.

and you need to use jquery

$(document).ready(function () {
  // the current page url eg /index.jsp
  var href = window.location.href.toLowerCase();
  
  $(".menu").find("a").each(function () {
    // find the current li that match the current Url
    if (href.indexOf($(this).attr("href").toLowerCase()) != -1)
           $(this).addClass("active"); // set the current li to active
     })
 })
.acive{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
    <ul>
       <li><a href="index.jsp" class="active">Home</a></li>
       <li><a href="listnews.jsp">News</a></li>
       <li><a href="abc.jsp">ABC</li>
    </ul>
</div>
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31