nickck15 nickck15 - 1 month ago 12
HTML Question

jQuery - Selecting active dots for li's and removing active class from others

I have a side navigation ul menu with a series of li's, for demonstrative purposes at the moment.

The first automatically uses the activeDot class, and when another is clicked the new dot uses this class, removing the class from the previously selected dot, but I have a problem where once a new dot uses the activeDot class and another dot is clicked on, the class isn't then removed from the previously-clicked dot. Only one dot should be active at a time, which I have tried to implement into my jQuery.

EDIT: Okay, now I've found out the jQuery isn't actually working at all in JSFiddle even though it's the same code.

JSFiddle: https://jsfiddle.net/Lusru678/.

JS:

$(document).ready(function() {

var currentDot = $('#aboutSideNav > ul > li.activeDot');

$('#aboutSideNav > ul > li').click(function() {

$(this).addClass('activeDot');
currentDot.removeClass('activeDot');

});

$('#aboutSideNav > ul > li.activeDot').click(function() {

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

});

});


HTML:

<div id="aboutSideNav" class="sideNav" style="margin-top:-100px">

<ul>

<li class="activeDot"></li>

<li></li>

<li></li>

<li></li>

</ul>

</div>


CSS:

.sideNav
{
position:absolute;
width:auto;
top:0;
right:0;
height:100%;
z-index:99;
display:flex;
align-items:center;
}

.sideNav > ul
{
margin:0;
padding:0;
}

.sideNav > ul > li
{
position:relative;
display:block;
margin:25px 30px;
width:4px;
height:4px;
cursor:pointer;
background:#fff;
border:2px solid #fff;
border-radius:50%;
transition:all linear 0.3s;
-webkit-transition:all linear 0.3s;
-moz-transition:all linear 0.3s;
}

@media only screen
and (max-width: 768px)
{
.sideNav > ul > li
{
width:8px;
height:8px;
}
}

.sideNav > ul > li.activeDot
{
background:transparent;
}

.sideNav > ul > li:hover
{
background:transparent;
border:2px solid #fff;
}

Answer

you only need one more line to make

Only one dot should be active at a time

happen

$(document).ready(function() {
     var currentDot = $('#aboutSideNav > ul > li.activeDot');

$('#aboutSideNav > ul > li').click(function() {
    $('li.activeDot').removeClass('activeDot'); // this line
    $(this).addClass('activeDot');
   // currentDot.removeClass('activeDot');//no longer needed

});  

  /*  $('#aboutSideNav > ul > li.activeDot').click(function() {

    $(this).addClass('activeDot'); // this li has class activeDot - why do you need this?

   });*/

});

and now as a one liner

 $('#aboutSideNav > ul > li').click(function() {
    $(this).addClass('activeDot').siblings().removeClass('activeDot'); 
})

The original element is not included among the siblings, which is important to remember when we wish to find all elements at a particular level of the DOM tree

from https://api.jquery.com/siblings/