Saturday, August 05, 2006

Check an HTML element is in view

ajaxMost of the web page that I created contains a form to let the user enters data. Generally, I put a customized ASP.NET's validation summary control to validation errors in the unified way. Since this is a customized control, I also use the control to display the status of an AJAX operation whether successful or not.

Whenever I display a message, I want to immediately grab user's attention. Initially, I call object.scrollIntoView. This is an IE specific method that scrolls the screen so that the corresponding object is in view. As the result, the element is either aligned at the top or bottom of the screen. This is OK, but what happen next is when the object is already in view, the screen jiggles and changes the position so that the object is position on the top. Quite an annoying experience for the user!

So I write this Javascript function that will check whether an object is in view.

The function accepts two parameters: the reference to the object (HTML element) and a boolean value bWhole. If you set bWhole to false, the function will only check the top-left corner of the element. It will return true if the top-left corner of the element is within the viewable area. However, if bWhole is to false, the function checks both top-left and bottom-right corners are within viewable area.


function isInView(o,bWhole) {
if(typeof(o)=='undefined' !o) return false;
if
(typeof(bWhole)=='undefined') bWhole=false;
var
x1=o.offsetLeft;
var
y1=o.offsetTop;
var
p=o;
while
(p.offsetParent) {
p
=p.offsetParent;
x1+=p.offsetLeft;
y1+=p.offsetTop;
}
var x2=x1+o.offsetWidth-1;
var
y2=y1+o.offsetHeight-1;
var
left=document.body.scrollLeft;
var
right=left+document.body.clientWidth-1;
var
top=document.body.scrollTop;
var
bottom=top+document.body.offsetHeight-1;
return
(bWhole)? (x1>=left && x2<=right && y1>=top && y2<=bottom) : (x1>=left && x1<=right && y1>=top && y1<=bottom) (x2>=left && x2<=right && y2>=top && y2<=bottom);
}

No comments: