Toggle occupied cells and update monitor

by carlbeech

HTML

<!--
Source - https://stackoverflow.com/a/74296304
Posted by Mark Schultheiss, modified by community. See post 'Timeline' for change history
Retrieved 2026-07-29, License - CC BY-SA 4.0
-->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-table">
  <div class="cell-mate">bunk Able</div>
  <div class="cell-mate">bunk Bravo</div>
  <div class="cell-mate">bunk Cat</div>
  <div class="cell-mate">bunk Dog</div>
  <div class="cell-mate">bunk Elephant</div>
  <div class="cell-mate">bunk Giraffe</div>
</div>
<div id="monitor"></div>

CSS

/*
Source - https://stackoverflow.com/a/74296304
Posted by Mark Schultheiss, modified by community. See post 'Timeline' for change history
Retrieved 2026-07-29, License - CC BY-SA 4.0
*/

.occupied {
  border: solid 1px #0000ff;
}

#monitor {
  border: dashed 2px #ddffdd;
  margin: 1em;
}

.next-up {
  background-color: #ffdddd;
}

JavaScript

// Source - https://stackoverflow.com/a/74296304
// Posted by Mark Schultheiss, modified by community. See post 'Timeline' for change history
// Retrieved 2026-07-29, License - CC BY-SA 4.0

$("#main-table").on('click', '.cell-mate', function(event) {
  let cells = $('.cell-mate');
  cells.toggleClass("occupied next-up", false);
  $(this).toggleClass("occupied");
  let myIndex = $(this).index();
  let clickNext = $(this).index() == cells.last().index() ? cells.first() : $(this).next('.cell-mate');
  clickNext.trigger('cellClick', [$(this), myIndex, clickNext]);
});
$('.cell-mate').on('cellClick', function(event, cell, prevIndex, nextUp) {
  nextUp.toggleClass('next-up');
  $('#monitor').html(cell.html() + " at " + prevIndex + " nudged " + nextUp.html() +
    " at " + nextUp.index());
});
//start it all off (or comment out to start with a user action)
$("#main-table").find('.cell-mate').eq(0).trigger('click');