Skip to content

Instantly share code, notes, and snippets.

@awran5
Last active October 23, 2018 22:27
Show Gist options
  • Save awran5/7c31c703fa0b72e5babedea5acc3cf1b to your computer and use it in GitHub Desktop.
Save awran5/7c31c703fa0b72e5babedea5acc3cf1b to your computer and use it in GitHub Desktop.
Basic CMB2 slider field based on HTML5 range input

This originally was based on slider field

I've changed its structure to avoid loading of heavy jquery UI so its only used the basic HTML5 type range input

1. php Filter

function cmb2_render_range( $field, $field_escaped_value, $field_object_id, $field_object_type, $field_type_object ){

  $slider = $field_type_object->input( array(
    'type'  => 'range',
    'class' => 'cmb2-range',
    'start' => absint( $field_escaped_value ),
    'min'   => $field->min(),
    'step'  => $field->step(),
    'max'   => $field->max(),
    'desc'  => '',
	) );

	$slider .= '<span class="range-text">' . $field->value_label() . ' <span class="range-value"></span></span>';
	$slider .= $field_type_object->_desc(true);
	echo $slider;
}
add_filter( 'cmb2_render_range', 'cmb2_render_range', 10, 5 );

2. CSS

/* Range field */
.cmb2-range {
  width: 70%;
  float: left;
  opacity: 0.75;
  -webkit-transition: .2s;
  transition: opacity .2s;
}
.cmb2-range:hover {
  opacity: 1;
}
.range-text {
  display: inline-block;
  margin: 0 .5rem
}
@media screen and (max-width:782px) {
  .cmb2-range {
    width: 100%;
    float: none;
  }
  .range-text {
    margin: .5rem 0
  }
}

3. jQuery

// CMB2 range
$('.cmb2-range').each(function() {
    var span = $('.range-value');
    span.html('<strong>' + $(this).val() + '</strong>' );
    // Append the range value to each slider 
    $(this).on('input', function() {
      // update to the dynamic value
      span.html('<strong>' + $(this).val() + '</strong>' );
    });           
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment