DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

HitTest //JavaScript Function

11.24.2005
| 13681 views |
  • submit to reddit
        <a href="http://jsfromhell.com/geral/hittest">
With this it's possible to correct the "SELECT over DIV" IE bug as i showed in the example bellow

it checks one element (or an array of them) against another one and returns the itens that matched the hit test (if the element superposes the other one in any place)

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/geral/hittest [v1.0]

hitTest = function(o, l){
	function getOffset(o){
		for(var r = {l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight};
			o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
		return r.r += r.l, r.b += r.t, r;
	}
	for(var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
		b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
		&& (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
	return j ? !!r.length : r;
};

usage
<style type="text/css">
#menu{position: absolute; height: 500px; width: 200px; display: none; border: 1px solid #999; background: #eef;}
</style>

<div id="menu">
    <input type="button" onclick="hide();" value="Hide Menu" />
</div>
<form action="">
    <fieldset>
    <strong>DIV x SELECT</strong>
    <br /><select><option>DIV OVER SELECT DIV OVER SELECT DIV OVER SELECT</option></select>
    <input type="button" onclick="show();" value="Show Menu" />
    </fieldset>
</form>


<script type="text/javascript">
//<![CDATA[

var x = document.getElementById("menu");

//exemplo de como consertar o problema do select em cima do div, como só acontece no IE, é possível sniffar o browser...

function show(){
    x.style.display = "block";
    if(!x.ieFix)
        x.ieFix = hitTest(x, document.getElementsByTagName("select"));
    for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "hidden");

}

function hide(){
    x.style.display = "none";
    for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "visible");
}

//]]>
</script>