I wonder if users click "test 1" will add class active in sidebar anchor and add background to expand list "#bar1".
the result should be sidebar font will red, and expand list background will red
But,what I found here if I click "test 1" it wont add class to anchor. Please is there anyone can help me to correct my code
$(document).ready(function(){
$('.sidebar li a').click(function(e){
e.preventDefault();
$(this).addClass('active');
$(this).removeClass('active');
var exId=$(this).attr('href');
$(exId).addClass('expandBg');
$(exId).siblings().removeClass('expandBg')
})
});
a.active{
text-decoration: none;
color: #f00;
}
.expandBg{
background-color:#f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
<ul>
<li><a href="#bar1">test 1</a></li>
<li><a href="#bar2">test 2</a></li>
<li><a href="#bar3">test 3</a></li>
<li><a href="#bar4">test 4</a></li>
</ul>
</div>
<div class="expand">
<ul>
<li id="bar1">bar1</li>
<li id="bar2">bar2</li>
<li id="bar3">bar3</li>
<li id="bar4">bar4</li>
</ul>
</div>
this line of code $(this).removeClass('active');
make an issue we want to remove active
class from siblings
anchor tag please find below snippet to know how to do that
$(document).ready(function(){
$('.sidebar li a').click(function(e){
e.preventDefault();
debugger;
$(this).addClass('active');
$(this).parent().siblings().find("a").removeClass("active")
var exId=$(this).attr('href');
$(exId).addClass('expandBg');
$(exId).siblings().removeClass('expandBg')
})
});
a.active{
text-decoration: none;
color: #f00;
}
.expandBg{
background-color:#f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
<ul>
<li><a href="#bar1">test 1</a></li>
<li><a href="#bar2">test 2</a></li>
<li><a href="#bar3">test 3</a></li>
<li><a href="#bar4">test 4</a></li>
</ul>
</div>
<div class="expand">
<ul>
<li id="bar1">bar1</li>
<li id="bar2">bar2</li>
<li id="bar3">bar3</li>
<li id="bar4">bar4</li>
</ul>
</div>