billybobjones
billybobjones

Reputation: 513

how to remove active state on other links when another link is active

I only want one link to be in an active state. How do I remove link's active state when I click on other links to make that specific link active instead? I'm using jQuery addClass and removeClass

Here's what I've got

<style>.active {border-bottom: 3px solid #DB3030;}</style>

<div class="link"><a href="#scroll1" class="scroll">Link 1</a></div>
<div class="link"><a href="#scroll2" class="scroll">Link 2</a></div>
<div class="link"><a href="#scroll3" class="scroll">Link3</a></div>


$(document).ready(function(){
    $(".link a").click(function() {
        $(this).siblings().removeClass('active').end().addClass('active');
    });
});

Upvotes: 0

Views: 2737

Answers (3)

Hemal
Hemal

Reputation: 3760

You can use following

var links = $(".link a"); 
$(links).click(function() {
    $(links).removeClass('active');
    $(this).addClass('active');
});

Upvotes: 1

Deepak Yadav
Deepak Yadav

Reputation: 7109

$(document).ready(function() {
  $(".link a").click(function() {
    $('.link a').removeClass('active');
    $(this).addClass('active');
  });
});
.active {
  border-bottom: 3px solid #DB3030;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="link"><a href="#scroll1" class="scroll">Link 1</a>
</div>
<div class="link"><a href="#scroll2" class="scroll">Link 2</a>
</div>
<div class="link"><a href="#scroll3" class="scroll">Link3</a>
</div>

Upvotes: 2

Adam Azad
Adam Azad

Reputation: 11297

Use

$(".link a").removeClass('active');

Then

$(this).addClass('active');

So your full code (and optimized);

var links = $(".link a"); // Cache the links for better performance
$(links).click(function() {
    $(links).removeClass('active');
    $(this).addClass('active');
});

Upvotes: 1

Related Questions