Determine if div appears between two separate div's
Been searching high and low and can't seem to find an answer to this one. I've got a page full of small square divs and am trying to come up with a method to check and see if a div falls in between two other divs on the page. For example:
Two div's normal:
[A]---------[B]
Page changes and loads a third div:
[A]---[C]---[B]
Assuming div's are 10px high, what would be the easiest way to determine if C fell at any point in between A and B?
Hopefully I explained it well enough, thanks 开发者_如何学Pythonfor the hand!!
Edit to add more detail, don't think I explained it well enough. I'm looking to find if the middle div is between A and B using the 'physical' locations on the page.
Say div A's top/left offset is 0,10 and div B is at 0,100. Each div is 10px tall so I'm trying to figure the simplest way to determine that div C falls in between them if it's top/left is at say 9,50. Hope that's a bit clearer.
Assuming this HTML:
<body>
<div class="someClass"></div>
<div class="someOtherClass"></div>
<div class="aClass"></div>
<div class="alsoaClass"></div>
</body>
Now, jQuery's index
will tell you what position that DIV is in:
$('.someClass').index(); // 0
$('.someOtherClass').index(); // 1
$('.aClass').index(); // 2
$('.alsoaClass').index(); // 3
Like this, you can always compare their positions in DOM.
If what you're trying to do is get the position relative to the window (not according to their DOM positions), then you should check their offset
:
$('.someClass').offset().top; // will give you amount of pixels from the top of the document
On the assumption that the divs share a common parent and are displayed in DOM order:
The .index() property is probably what you are after
Documentation: http://api.jquery.com/index/
Example: http://jsfiddle.net/Y7aWM/4/
function between(before, current, after)
{
var $current = $(current);
var $before = $current.parent().children(before);
var $after = $current.parent().children(after);
var before_index = $before.index();
var current_index = $current.index();
var after_index = $after.index();
return (before_index < current_index && current_index < after_index );
}
I cannot vouch for the reliability, but the DOM clientTop property might be of some interest.
https://developer.mozilla.org/en/DOM/element.clientTop
function checkPosition(divID)
{
if($('#'+divID).next().attr('nodeName') == 'DIV' && $('#'+divID).prev().attr('nodeName')=='DIV')
alert('its between two divs');
}
I hope this helps
精彩评论