There are numerous ways in which one can add active
class to a link. One way is to use if
statements to do so. Modern JS frameworks such as Angular, React and VueJS support route-link
designed to manage routes in the application. The same effect can also be achieved with jQuery. It is certainly a much neater solution than using if
statements throughout our code base. Using jQuery has the additional benefits of not slowing down the loading of the website.
Provided the links on your website are reasonably well optimized for SEO, the following piece of code should handle selecting the appropriate hyperlink. Just add it at the end of your _Layout
file :
1 |
$('a[href="' + window.location.pathname + '" i]').addClass('active'); |