Is website prefore by hand? Is auto good?

class like this code: Link

I don’t know how to ask.
This question sound stupid.

Are you asking if the “active” class needs to be added manually to each page? The answer is no, it doesn’t. You can use PHP or other scripting language to add it automatically.

Yes. So use those of language to make it work is simple things?

It would be easier to answer if I had a better idea of what you want to achieve.

Do you really need a method to insert the class automatically, or are you just looking for the best way to achieve the result in the example?

@ronpat has provided a “matching pairs” technique which might be sufficient for your needs without any need for scripting. See this recent discussion: Nav link colour change

1 Like

Thank so much!
I feel curious about the code so just want to know about the system.

I use a PHP include to add my menu to each page, and set it up something like this:

<?php $currentPage =  basename($_SERVER['SCRIPT_NAME']); ?>

		<ul class="mainNav">
			<li><a <?php if ($currentPage == 'index.php') {echo 'class="current"';} ?> href="index.php">Home</a></li>
			<li><a <?php if ($currentPage == 'hire.php') {echo 'class="current"';} ?> href="hire.php">Hire</a></li>
			<li><a <?php if ($currentPage == 'repairs.php') {echo 'class="current"';} ?> href="repairs.php">Repairs</a></li>
			<li><a <?php if ($currentPage == 'sales.php') {echo 'class="current"';} ?> href="sales.php">Sales</a></li>
			<li><a <?php if ($currentPage == 'contact.php') {echo 'class="current"';} ?> href="contact.php">Contact</a></li>
		</ul>	

It checks to see which page is in the current URL, and then adds the “current” class to the matching menu item.

2 Likes

If you want to dynamically apply an active class to in-page navigation links (like in that w3schools example), you’ll need JS though. The cool thing about this however is that it works for any links – along the lines of

var links = document.querySelectorAll('a')

var applyActive = function () {
  var current
  var i

  for (i = 0; i < links.length; i++) {
    current = links[i]

    if (current.href === window.location.href) {
      current.classList.add('active')
    } else {
      current.classList.remove('active')
    }
  }
}

window.addEventListener('hashchange', applyActive)
applyActive()
3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.