Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bbbenji/7745e0ff7b8d7badcc12443eb8f8aa3e to your computer and use it in GitHub Desktop.
Save bbbenji/7745e0ff7b8d7badcc12443eb8f8aa3e to your computer and use it in GitHub Desktop.
Bootstrap 4 cardinal direction range input

Bootstrap 4 cardinal direction range input

Range input for selecting cardinal direction and outputting degrees from north using Bootstrap custom-range input and native JavaScript.

A Pen by Benji on CodePen.

License.

%form
.form-group
%label.mb-0{:for => "orientation"} Orientation: <strong><span id="degrees"></span>° (<span id="direction"></span>)</strong>
%input.custom-range.px-3{:type => "range", :id => "orientation", :min => 0, :max => 360, :step => 1, :value => 145}
#div.ticks.d-flex.justify-content-between.text-monospace.px-3
- @item = ['N', '', 'NE', '', 'E', '', 'SE', '', 'S', '', 'SW', '', 'W', '', 'NW', '', 'N']
- @item.each_with_index do |item, index|
%span= item
function setCardinalDirection() {
const value = document.getElementById('orientation').value; // Get current value from range input
document.getElementById('degrees').textContent = value; // Inject current input value into label
const direction = document.getElementById('direction'); // Define intercardinal direction display element
const degrees = 22.5; // Define range between two intercardinal directions
const cardinal = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'];
let cardinalOut = cardinal[Math.floor((value / degrees) + 0.5)];
direction.textContent = cardinalOut; // Inject current cardinal value into label
};
window.addEventListener('load', setCardinalDirection); // Execute on page load
document.getElementById('orientation').addEventListener('input', setCardinalDirection); // Execute when on value change
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
body {
max-width: 900px;
margin: 25px auto 0;
}
.ticks {
padding-bottom: 1rem;
span {
display: flex;
justify-content: center;
width: 1px;
background: #D3D3D3;
height: 5px;
line-height: 35px;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment