user3433046 user3433046 - 4 months ago 9
Javascript Question

Add class to current and previous list items

I have an unordered list used as a menu to play sections of a video. The list item (video portion) that's playing highlights when clicked by adding a class to it and removing the class from any other list item. I've been asked by the client to change this so that if you click on an item, the previous list items are selected also. Namely if you click on Vid 2, then Vid 1 and Start are given the 'selected' class as well as Vid 2. Clicking on Vid 3, would highlight Vid 3, Vid 2, Vid 1, Start and so on.

I would also like to remove the selected class from any list item that's ahead of the clicked item. For instance if Vid 4 is selected and the user clicks on Vid 2, then the selected class is removed from Vid 4 and Vid 2, Vid 1 and Start have the class selected. Sorry if any of this makes little sense and thanks in advance.



$("#select li a").click(function() {
$(this).parent().addClass('selected').siblings().removeClass('selected');
});

#video-controls ul li {
cursor: pointer;
}

#video-controls ul li a {
color: #5f6a72;
text-decoration: none;
display: block;
}

#video-controls ul li.selected,
#video-controls ul li.selected a {
color: #00aad2;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<nav id="video-controls">
<ul id="select">
<li id="start"><a href="#/">Start</a></li>
<li id="vid-1"><a href="#/">Vid 1</a></li>
<li id="vid-2"><a href="#/">Vid 2</a></li>
<li id="vid-3"><a href="#/">Vid 3</a></li>
<li id="vid-4"><a href="#/">Vid 4</a></li>
</ul>
</nav>




Answer

You can

1) traverse and get all previous elements.

2) use .andSelf() to add clicked object parent

3) add class selected to all elements returned above.

4) find remaining siblings other than returned element in step 2

5) remove class selected

$("#select li a").click(function() {
 $(this).parent().prevAll().andSelf().addClass('selected').filter(':last').nextAll().removeClass('selected');
});
#video-controls ul li {
	cursor: pointer;
}

#video-controls ul li a {
	color: #5f6a72;
	text-decoration: none;
	display: block;
}

#video-controls ul li.selected,
#video-controls ul li.selected a {
	color: #00aad2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<nav id="video-controls">
  <ul id="select">
    <li id="start"><a href="#/">Start</a></li>
    <li id="vid-1"><a href="#/">Vid 1</a></li>
    <li id="vid-2"><a href="#/">Vid 2</a></li>
    <li id="vid-3"><a href="#/">Vid 3</a></li>
    <li id="vid-4"><a href="#/">Vid 4</a></li>
  </ul>
</nav>

Comments