Search code examples
javascripthtmlcssdrag

How to drag or move a span into the Div by using javascript


How to move or drag the span into the Div element. My element structure is the Div -> Span. Here I need to drag the Span inside the div element without drag beyond that div. I have tried this by calculating pixels but didn't give a solution. I don't need a native onDrag method.

I need to calculate pixels and drag the Span inside the Div. Here is my code.

var handleClick = false;

window.dragging = function(event) {
  if (handleClick) {
    var bar = document.getElementsByClassName('bar')[0],
      handle = document.getElementsByClassName('handle')[0];
    var left = bar.offsetWidth - handle.offsetWidth;
    tops = (bar.offsetWidth - handle.offsetWidth);
    pixel = left < ((pixel - 0) / 1.233445) ? left : ((pixel - 0) / 1.233445);
    handle.style.left = pixel + "px";
  }
}

document.addEventListener('mouseup', function() {
  handleClick = false;
});

window.handlersDown = function() {
  handleClick = true;
}
.bar {
  width: 100px;
  height: 30px;
  border: 1px solid;
  position: relative;
}

.handle {
  width: 20px;
  height: 20px;
  left: 2px;
  top: 5px;
  background-color: rgba(255, 0, 0, 0.5);
  position: absolute;
}
<div class="bar">
  <span class="handle" onmousedown="handlersDown()" onmousemove="dragging(event)"></span>
</div>


Solution

  • I have modified your code a bit and changed the selectors from class to ID. I also would advice you to use external libraries to make it more easy for you. Besides that I also removed the event listeners inside your HTML and translate them to Javascript. Is this what you want?

    window.onload = addListeners();
    
    function addListeners(){
        document.getElementById('handle').addEventListener('mousedown', mouseDown, false);
        window.addEventListener('mouseup', mouseUp, false);
    }
    
    function mouseUp()
    {
        window.removeEventListener('mousemove', spanMove, true);
    }
    
    function mouseDown(e){
      window.addEventListener('mousemove', spanMove, true);
    }
    
    function spanMove(e){
    		var bar = document.getElementById('bar')
        var span = document.getElementById('handle');  	
        
        // variables 
        var bar_width = bar.offsetWidth; 
        var handle_width = span.offsetWidth;
        
        // stop scroll left if the minimum and maximum is reached
        if(e.clientX < bar_width - handle_width - 1 && e.clientX > 1){
      		span.style.left = e.clientX + 'px';
        }
    }
    #bar {
      width: 100px;
      height: 30px;
      border: 1px solid;
      position: relative;
    }
    
    #handle {
      width: 20px;
      height: 20px;
      left: 2px;
      top: 5px;
      background-color: rgba(255, 0, 0, 0.5);
      position: absolute;
    }
    <div id="bar">
      <span id="handle"></span>
    </div>