2

I have several absolute positioned elements. Is it possible to get all elements with a position that's to the right of the current element?

If yes, how to do this?

Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
Mirgorod
  • 31,413
  • 18
  • 51
  • 63
  • You should be able to do this via `.position()`: http://api.jquery.com/position/ and `.offset()`: http://api.jquery.com/offset/ – m90 Oct 28 '11 at 08:40

2 Answers2

2

I've just written a plugin which implements this feature. Fiddle: http://jsfiddle.net/FJ5Cp/1/

The function logic should bbe similar to:

  1. Get the current element's left position and offset width. Add these together to get the right border.
  2. Get the left position and offset width of each element, add these to get the right border. Compare this value to the value at one.

Usage and function:

// Basic usage
var allRightElements = $("element").rightOfCurrent();
// Only select ___ elements which are located right of the current element
var allRightElementsFilter = $("element").rightOfCurrent("___");
// Only select ___ elements, which are located right of the current element,
//   which are childs of ####
var allRightFilterInsideSomething = $("element").rightOfCurrent("___", "###");

(function($){
    $.fn.rightOfCurrent = function(selector, context){
        elem = this.eq(0);
        selector = selector || '*';
        context = context || null;
        var currentRight = elem.offset().left + elem.width();
        return $(selector, context).filter(function(){
           var $this = $(this);
           if ($this.css('position') == 'absolute'){
               return $this.offset().left + $this.width() > currentRight;
           }
           return false;
        });
    }
})(jQuery);
Rob W
  • 341,306
  • 83
  • 791
  • 678
0

Use .filter(), comparing each element's .offset().left with that of the current element:

var l = currentElement.offset().left;
var righterElements = positionedElements.filter(function(){
    return $(this).offset().left > l;
});
gilly3
  • 87,962
  • 25
  • 144
  • 176