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.
Asked
Active
Viewed 154 times
1
-
Similar here http://stackoverflow.com/questions/2013902/select-cells-on-a-table-by-dragging – kiranvj Jun 14 '12 at 13:02
-
1i refer ur question but i wanna use in javascript strictly – Jun 14 '12 at 13:11
-
Should it work in all browsers or are you targeting only few browsers? – kiranvj Jun 14 '12 at 13:18
1 Answers
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>