Wosley Alarico Wosley Alarico - 21 days ago 6
CSS Question

Adding class active on one click only

I am trying to add a class active, every time a click on a link but for now, it is only adding if I double click on it.

Here my HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="content">
<ul>
<li><a href="#">Deposit</a></li>
<li><a href="#">Account</a></li>
<li><a href="#">Credit</a></li>
</ul>
<div class="box active" id="deposit">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio sunt voluptates reprehenderit similique nostrum eius repudiandae odio eos obcaecati doloremque quam quos, officiis veritatis blanditiis soluta molestiae iusto illo corrupti.</p>
</div>
<div class="box" id="account">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio sunt voluptates reprehenderit similique nostrum eius repudiandae odio eos obcaecati doloremque quam quos, officiis veritatis blanditiis soluta molestiae iusto illo corrupti.</p>
</div>
<div class="box" id="credit">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio sunt voluptates reprehenderit similique nostrum eius repudiandae odio eos obcaecati doloremque quam quos, officiis veritatis blanditiis soluta molestiae iusto illo corrupti.</p>
</div>

</div>
<div id="random">
<p>This is a random text</p>
</div>


CSS:

li{
list-style:none;
color: white;
width: 30%;
a{
color: white;
text-decoration: none;
&:hover{
color: blue;
}
}

}
ul{
background: black;
padding: 20px 0;
text-align: center;
display: flex;
justify-content: center;
}
.box{
height: 200px;
}
#deposit{
background: green;
}
#account{
background: pink;
}
#credit{
background: blue;
}
li a.active{
color: red;
}


JS:

$(document).ready(function(){

$('div.box').hide();
$('li a').on("click", function(){

if(!$('li a').hasClass('active')){
$(this).addClass('active');
}
else{
$('li a').removeClass('active');
}
});
});


Here my pen: http://codepen.io/Sidney-Dev/pen/MbyXvP

How can I add the class active to the link when I click on it and remove that same class from any other link if it exists?
Hope you can help.

Answer

Just remove active class from all a and then add active class to clicked a like following.

$('div.box').hide();
$('li a').on("click", function(){
    $('li a').removeClass('active'); 
    $(this).addClass('active');     
});  

UPDATED CODEPEN

Comments