javascript - jQuery I want to add an active class to the linked ID of an anchor tag -


i've written alphabet navigation program- have anchor linked linked h4 tags. when click a-tag, want element matching id have class of active. when click anchor tag, removes class of active , assigns element. here's have far:

<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" 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>   $("scroller").on("click", function(){ function matchalpha(){ var matchid = $(this).attr("href"); find.$(matchid).find.$(alpha-heading).removeclass("active"); find.$(matchid).find.$(this).$(alpha-heading).addclass("active"); }  }); 

you can reduce code single line in click handler:

$('.scroller').click(function() {    $($(this).attr('href')).addclass('active').siblings().removeclass('active')  })
.active {    background: #faa;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <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" 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>

the way works follows:

  • $('.scroller').click(function() {: when clicking on link scroller class
  • $(this).attr('href') href attribute
  • select , add active class .addclass('active')
  • the select siblings of element , remove active class .siblings().removeclass('active')

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -