- This topic is empty.
-
AuthorPosts
-
September 15, 2016 at 2:46 pm #245601johnedParticipant
How do you make the page I am on stay highlighted while I am on that page? Right now I have figured how to make it change color by hovering over it but I cant figure out how to make it stay a certain color when I am not hovering over it.
This is the code I am using so farHTML-
< div> <nav> <ul class="nav"> <li><a href="home2.html">HOME</a></li>
CSS –
.active { background-color: red; }
September 15, 2016 at 3:36 pm #245605Paulie_DMemberGenerally, you need javascript to compare the current page url to those in your nav and apply the
.active
class.On very small sites you can apply classes to the
body
to effect this but JS is the usual method.September 15, 2016 at 9:46 pm #245617johnedParticipantI am not very familiar with javascript. Can you push me in the right direction on how to do this with javascript?
ThanksSeptember 16, 2016 at 2:07 am #245623BeverleyhParticipantGoogling something like “highlight current page in menu with javascript” will lead you to various solutions.
But, as luck would have it, I wrote a quick script function for a recent project;
function navHighlight(elem, home, active) { var url = location.href.split('/'), loc = url[url.length -1], link = document.querySelectorAll(elem); for (var i = 0; i < link.length; i++) { var path = link[i].href.split('/'), page = path[path.length -1]; if (page == loc || page == home && loc == '') { link[i].parentNode.className += ' ' + active; document.body.className += ' ' + page.substr(0, page.lastIndexOf('.')); } } } navHighlight('.menu a', 'index.php', 'current'); /* menu link selector, home page, highlight class */
This does as Paulie described – it compares the page file name from the URL to any hrefs in the menu, and if they match, it adds a class to the anchor’s parent li.
Additionally, it adds the page name as a class to the body tag.
So, using the example above, if you were viewing the “about-us.php” page in a web browser, the menu li for “About Us” gets a “.current” class, and the body element get a “.about-us” class;
<body class="about-us"> <ul class="menu"> <li><a href="/index.php">Home</a></li> <li class="current"><a href="/about-us.php">About Us</a></li> <li><a href="/contact-us.php">Contact Us</a></li> </ul>
Note that the navHighlight() function takes 3 parameters;
– the CSS selector to the a elements in the menu
– the file name of the home page
– the class you want to give current/active menu itemsPop it above the closing </body> tag.
-
AuthorPosts
- The forum ‘CSS’ is closed to new topics and replies.