I have a number of elements with the same class like this:
<html>
<head><title>example</title>
<script type="text/javascript" src="jquery.js">
</head>
<body>
<ul>
<li class="togglebutton">elem1</li>
<li class="togglebutton">elem2</li>
<li class="togglebutton selected">elem3</li>
<li class="togglebutton">elem4</li>
</ul>
$(document).ready(function(){
});
</body>
</html>
The selected element has a different color from the other elements. When a user clicks on ANOTHER element, I want that element to have the selected class - and all other elements should no longer have the selected class. In other words, only one element can be selected at any time.
I think I have worked out the logic, but I am not sure how to implement it using jQuery.
basically my approach would be:
(When an item is selected):
- Select all items using selector "ul > li.togglebutton"
- remove class 'selected' from all of the items fetched in step 1
- add class 'selected' to the current element that was clicked on.
Is this logic correct, or is there a better way of going about it?
Also, how may I implement the above logic (assuming there is no better alternative), using jQuery?