Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/ee033ef17e1da3751b49c88830835f28 to your computer and use it in GitHub Desktop.
Save mtvbrianking/ee033ef17e1da3751b49c88830835f28 to your computer and use it in GitHub Desktop.
jQuery single vs multiple selection
<!DOCTYPE html>
<html>
<head>
<title>jQuery Single vs Multiple Selection</title>
<style>
.items {
padding: 0;
margin: 0;
list-style: none;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row;
justify-content: space-around;
line-height: 30px;
}
.item {
background: tomato;
margin: 5px;
color: white;
font-weight: bold;
font-size: 1.5em;
text-align: center;
flex: 1 0 auto;
height: auto;
}
.item:before {
content: '';
float: left;
padding-top: 100%;
}
.item.selected {
background: red;
}
</style>
</head>
<body>
<div class="items">
<div class="item" data-alias="jdoe">John Doe</div>
<div class="item" data-alias="bking">Brian King</div>
<div class="item" data-alias="pwalker">Paul Walker</div>
</div>
<script src=""></script>
<script>
function addOrRemove(arr, obj, key) {
var index = arr.findIndex(function(el) {
return el[`${key}`] === obj[`${key}`];
});
if (index === -1) {
arr.push(obj);
} else {
arr.splice(index, 1);
}
return arr;
}
var selected = [];
$('.item').on('click', function(event) {
var user = {
alias: $(this).data('alias'),
name: $(this).html()
};
if (event.ctrlKey) {
$(this).toggleClass('selected');
selected = addOrRemove(selected, user, 'alias');
console.log(selected);
return;
}
$('.item').not(this).removeClass('selected');
// $(this).addClass('selected');
$(this).toggleClass('selected');
selected = $(this).hasClass('selected') ? [user] : [];
console.log(selected);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment