1

enter image description here

I want to drag the mouse on cell and whatever is under cells gets selected. only its under cell get selected. if user moves mouse zigzag way then no selection be happen.

Moe Far
  • 2,742
  • 2
  • 23
  • 41

1 Answers1

0

Here is my solution tested on Chrome. I was not sure if you wanted for the first square to be selected when you start dragging, so I left it unselected to not select it before you begin the zigzag.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
td{padding: 100px;}
.selected{background-color: #f55;}
.deselected{background-color: #faa;}
</style>
<script>
var dragging = false
var reference
addEventListener("load", function(){
  var squares = document.querySelectorAll("td")
  for(var i = 0; i < squares.length; ++i){
    squares[i].draggable = true
    squares[i].className = "deselected"
    squares[i].addEventListener("dragstart", function(){
      reference = this
      dragging = true
    })
    squares[i].addEventListener("drop", function(){dragging = false})
    squares[i].addEventListener("dragenter", toggle)
  }
})
function toggle(){
  if(!dragging) return
  if(this == reference) return
  var rect = reference.getBoundingClientRect()
  if(this.getBoundingClientRect().top < rect.top){
    dragging = false
    return
  }
  if(this.getBoundingClientRect().left != rect.left){
    dragging = false
    return
  }
  if(this.className == "selected"){
    this.className = "deselected"
  }
  else{
    this.className = "selected"
  }
}
</script>
</head>
<body>
<table>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</table>
</body>
</html>