jQuery toggleClass example

Toggle class name on click in jQuery

by moshfeu

HTML

<div class="range-wrapper clickable">
  <label for="value">VALUE</label>
  <span>Some Value</span>
  <input type="text" name="value" id="value" hidden>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  color: #eee;
}

.range-wrapper {
    display: flex;
    flex-direction: column;
    border: 1px solid white;
    border-radius: 5px;
    width: 10vw;
    height: 2rem;
}

.range-wrapper>label,
.range-wrapper>span {
    pointer-events: none;
}

.range-wrapper>label {
    text-align: left;
    font-size: x-small;
    font-weight: bold;
}

.range-wrapper>span {
    font-size: medium;
    font-weight: bold;
}

.clickable {
    cursor: pointer;
}

JavaScript

/**
 * Actions to be done once one of the div is clicked. 
 * It should hide the span, fade in the input, focus it, disable the self event and enable the input event.
 */
const rangeElement = $('.range-wrapper');
const input = rangeElement.find('input');
const span = rangeElement.find('span');

function toggle() {
  input.toggle().focus();
  span.toggle();
}

rangeElement.on('click', toggle);

/**
 * Actions to be done once one of the input loses focus or the enter key is pressed. 
 * It should hide the input, fade in the span, reenable the click event on the wrapper and disable self.
 */
$('.range-wrapper input')
  .on('keyup', function(e) {
    e.stopPropagation();
    if (e.type == 'keyup' && e.keyCode === 13) {
      $(this).blur();
    }
  })
  .on('focusout', function() {
    toggle();
    span.text(input.val() || 'Some Value')
  });

/* function rangeClickEvent(rangeElement) {
    $(rangeElement).children('span').hide();
    $(rangeElement).children('input').fadeIn(300).focus();
    $(rangeElement).off('click').removeClass('clickable');
}

function rangeFocusOutEvent(inputElement) {
    const parentDiv = $(inputElement).parent();
    $(inputElement).hide();
    $(parentDiv).children('span').fadeIn(300);
    setClickEventBack(parentDiv);
}

function setClickEventBack(rangeElement) {
    $(rangeElement).addClass('clickable');
    //line below - re-adding the click event causes trouble
    $(rangeElement).on('click', rangeClickEvent(rangeElement));
} */