How to select elements based on XY coordinates and not with mouse drag with jquery?
Asked
Active
Viewed 1,479 times
2

Davor Zubak
- 4,726
- 13
- 59
- 94
-
Should elements which are partially within that range be selected? – Rob W Dec 10 '11 at 14:21
-
no, just those that are completely selected! – Davor Zubak Dec 10 '11 at 14:26
1 Answers
3
The jQuery plugin, as shown below, will select all elements which are (partially) at position >= x and >= y.
(function($){
$.fn.filterXY = function(x, y){
return this.filter(function(){
var $this = $(this),
offset = $this.offset(),
width = $this.width(),
height = $this.height();
return offset.left + width >= x
&& offset.top + height >= y;
});
}
})(jQuery);
Examples:
$("*").filterXY(0,0);
$("div").filterXY(100, 0);
Update: Plugin to filter all elements between x1 and x2
Demo: http://jsfiddle.net/yx4sN/7/
(function($){
$.fn.inRangeX = function(x1, x2){
// Accepting selectors and DOM elements
if (typeof x1 == "string" && +x1 != x1 || x1 instanceof Element) {
x1 = $(x1);
}
if (typeof x2 == "string" && +x1 != x1 || x1 instanceof Element) {
x2 = $(x2);
}
// Accepting jQuery objects
if (x1 instanceof $) {
x1 = x1.offset().left;
}
if (x2 instanceof $) {
x2 = x2.offset().left;
}
x1 = +x1;
x2 = +x2;
// Make sure that x1 < x2
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;
}
return this.filter(function(){
var $this = $(this),
offset = $this.offset(),
rightSide = $this.width() + offset.left;
return offset.left >= x1
&& rightSide <= x2;
});
}
})(jQuery);

Rob W
- 341,306
- 83
- 791
- 678
-
can you take a look at http://jsfiddle.net/ingol/yx4sN/, where would i need to implement yours solution? – Davor Zubak Dec 10 '11 at 15:09
-
it always returns 99, as the sum of child elements, how to achieve that it returns only sum of elements on right of firstPicker and smaller(left) than secondPicker – Davor Zubak Dec 10 '11 at 15:36
-
thanks, can you explain how automaticly select those child elements that are in xy scope, using selectable()? – Davor Zubak Dec 10 '11 at 15:46
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/5740/discussion-between-rob-w-and-ingol) – Rob W Dec 10 '11 at 15:47
-
After some discussion, the final, desired solution is constructed, and can be found here: http://jsfiddle.net/ingol/yx4sN/9/ – Rob W Dec 10 '11 at 16:30
-
,can you take a look at this question, please? http://stackoverflow.com/q/8473404/765628 – Davor Zubak Dec 13 '11 at 08:45
-