jQuery I want to add an active class to the linked ID of an anchor tag style2.track360.xyz (ok)

https://stackoverflow.com/questions/45306883/jquery-i-want-to-add-an-active-class-to-the-linked-id-of-an-anchor-tag

2 cái này kết hợp với

https://app.gitbook.com/@javascriptuse/s/advanced/keep-url-unaffected-when-anchor-link-is-clicked-ok

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <title>Document</title>
  <style type="text/css" media="screen">
    .active {
      background: #faa;
    }
  </style>
</head>

<body>
  <ul class="no-bullet inline">
    <li><a class="scroller" href="#a"><strong>A</strong></a></li>
    <li><a class="scroller" href="#b"><strong>B</strong></a></li>
    <li><a class="scroller" href="#c"><strong>C</strong></a></li>
  </ul>
  <h4 class="alpha-heading active" id="a"><strong>A</strong></h4>
  <h4 class="alpha-heading" id="b"><strong>B</strong></h4>
  <h4 class="alpha-heading" id="c"><strong>C</strong></h4>
  <script type="text/javascript">
    $('.scroller').click(function() {
      $($(this).attr('href')).addClass('active').siblings().removeClass('active')
    })
  </script>
</body>

</html>

Full code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <title>Document</title>
  <style type="text/css" media="screen">
    .active {
      background: #faa;
    }
  </style>
</head>

<body>
  <ul class="no-bullet inline">
    <li><a class="scroller" href="#a"><strong>A</strong></a></li>
    <li><a class="scroller" href="#b"><strong>B</strong></a></li>
    <li><a class="scroller" href="#c"><strong>C</strong></a></li>
  </ul>
  <h4 class="alpha-heading active" id="a"><strong>A</strong></h4>
  <h4 class="alpha-heading" id="b"><strong>B</strong></h4>
  <h4 class="alpha-heading" id="c"><strong>C</strong></h4>
  <script type="text/javascript">
    $('.scroller').click(function(e) {
    	e.preventDefault();
    	var hash = this.hash;
      $($(this).attr('href')).addClass('active').siblings().removeClass('active');
      window.location.hash = "";
    })
  </script>
</body>

</html>

Last updated

Navigation

Lionel

@Copyright 2023