How To Add An Active Class On A Current Menu Item Page? Html
Solution 1:
Use simple Css to do that. use active class only on that li. and give the class css, like give it (Font-weight:bold; color:something;...etc). you have seprate pages for every link i guess. so when user goes to that link(that page). only that list will be have class active
Solution 2:
You can achieve this with a simple loop through the result of
document.querySelectorAll()
. inside the loop you have to compare the href of the element (<a>
tag) with thelocation.href
.Note that in the example below I have used an hard-coded string instead of
location.href
in the example below.var x = document.querySelectorAll('.menuul > li > a'); for (var i = 0; i < x.length; i++) { if (x[i].href == "https://stacksnippets.net/#/") { x[i].className += ' active'; } console.log(i + ' has the classes: ' + x[i].className); }
.active { color: red; }
<ulclass="menuul"><li><ahref="/#/"class="current">Начало</a></li><li><ahref="/#/muskulnamasa/">Действие</a></li><li><ahref="/#/sastavki/">Състав</a></li><li><ahref="/#/testosteron/">Тестостерон</a></li><li><ahref="/#/vuprosi/">FAQ</a></li><li><ahref="/#/mnenia/">Мнения</a></li><liclass="lastli"><ahref="/#/porachka/">ПОРЪЧАЙ</a></li></ul>
Solution 3:
If you use jQuery,
- Place the following code in a common javascript file which can be accessed by all the pages.
Get the ending of URL and use the same as ID for respected
<a>
elementurl = window.location.href; //Get the current URL. id = url.split("/").splice(-1); if(id == ""){ id = url.split("/").splice(-2); //URL ending with"/" } if(id != "" || type(id) != "undefined"){ $(".menuul #"+id).addClass("current"); }else{ $(".menuul li:first-child a").addClass("current"); }
In your HTML :
<ulclass="menuul"><li><ahref="/#/"class="current">Начало</a></li><li><aid="muskulnamasa"href="/#/muskulnamasa/">Действие</a></li><li><aid="sastavki"href="/#/sastavki/">Състав</a></li><li><aid="testosteron"href="/#/testosteron/">Тестостерон</a></li><li><aid="vuprosi"href="/#/vuprosi/">FAQ</a></li><li><aid="mnenia"href="/#/mnenia/">Мнения</a></li><liid="porachka"class="lastli"><ahref="/#/porachka/">ПОРЪЧАЙ</a></li></ul>
CSS :
Style your
current
CSS class accordingly.Solution 4:
ohh - it took me 4-5 hours to find it, so ... i paste the answer here- may be some1 can use it. i putted the following code in a file menu-active-file.js and pointed for it in the footer:
$(function () { var url = window.location.pathname, urlRegExp = newRegExp(url.replace(/\/$/, '') + "$"); $('a').each(function () { if (urlRegExp.test(this.href.replace(/\/$/, ''))) { $(this).addClass('active'); } }); });
Thanks for all the answers anyway.
Post a Comment for "How To Add An Active Class On A Current Menu Item Page? Html"