JSFiddle - React, Tailwind, and code Playground
HTML
<div id="timeline">
<div id="dragger" class="ui-draggable" style="left: 93px;"></div>
<div style="left: 16px;" class="keyframe 16px ui-draggable">left: 16px</div>
<div style="left: 197px;" class="keyframe 197px ui-draggable">left: 197px</div>
<div style="left: 432px;" class="keyframe 432px ui-draggable">left: 432px</div>
</div>
<div id="something"></div>
CSS
#timeline {
border:1px solid #333333;
height:20px;
position:relative;
width:620px;
font-size:10px;
font-family:Arial;
}
.keyframe {
background:#000033;
border:1px solid #333333;
display:inline-block;
height:6px;
position:absolute;
width:6px;
margin:5px 0 0 0;
}
#dragger {
background:red;
height:323px;
position:absolute;
width:20px;
}
#something { margin-top: 20px }
JavaScript
$(document).ready(function(){
$("#dragger").draggable({
containment: '#timeline',
axis: 'x',
drag: function(event, ui) {
var dragTime = $("#dragger").css("left");
$(this).text(dragTime);
},
stop: function(event, ui) {
var this_left = $(this).position().left;
var keyframes = $(".keyframe");
var closest_left = [null,0], closest_right = [null,0];
keyframes.each(function(index) {
var t = $(this);
var offset = t.position().left - this_left;
if (offset >= 0) {
if (closest_right[0] == null || offset < closest_right[1]) {
closest_right[0] = t;
closest_right[1] = offset;
}
}
else {
if (closest_left[0] == null || offset > closest_left[1]) {
closest_left[0] = t;
closest_left[1] = offset;
}
}
});
var str = "Closest left (blue) is " + closest_left[1] + "px to the left (relative to the bar).<br />";
str += "Closest right (yellow) is " + closest_right[1] + "px to the right (relative to the bar).<br />"; $("#something").html(str);
keyframes.css("background-color","");
$(closest_left[0]).css("background-color","blue");
$(closest_right[0]).css("background-color","yellow");
}
});
});