Toni Au Toni Au - 4 months ago 22
CSS Question

jQuery Toggle Width Logic

I'm trying get expanding/ collapsing tabs on click so it's easy for the user to see which tab they're currently on.

I think what I want to do is to traverse through

<div class="sidebar">
's children and check each one for
.hasClass('clicked')
.
During my traversal, if I find a child that has the class
.clicked
, I want to stop there,
.removeClass()
and
.addClass('clicked')
to whichever tab was originally clicked.

I'm not sure how to do this or if this is even the right way to approach at all.



$(".sidebar a").on('click', function() {

/*if( $(".sidebar").children().hasClass('clicked') ){
$(this).removeClass('clicked');
}*/

$(this).toggleClass('clicked');
});

.sidebar {
position: fixed;
width: 14.5%;
top: 0;
bottom: 0;
text-decoration: none;
float: left;
display: inline-block;
padding-top: 2%;
padding-bottom: 2%;
z-index: 500;
}

.sidebar a {
color: whitesmoke;
background-color: #404040;
padding: 26% 20% 26% 15% ;
text-decoration: none;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.2);
z-index: 800;
cursor: pointer;
width: 80%;
}

.item {
display: block;
}

.sidebar a.clicked {
width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="sidebar">

<a href="#" class="item"> Item 1 </a>
<a href="#" class="item"> Item 2 </a>
<a href="#" class="item"> Item 3 </a>

</div>




Answer

You can just add the class to the clicked sidebar item and then remove it from all its siblings in one go, like so:

$(".sidebar").on("click", ".item", function() {
    $(this).addClass("clicked").siblings(".item").removeClass("clicked");
    return false;
});
Comments