Tuesday, December 21, 2010

View port - keeping elemnets inside a view port

From days i faced issue to keeps  divs inside the visible region, but finally i was able to figure out how to do it.
its very simple.

Let me tell you some thing about the view ports now using JQuery :
View port is : region visible on your browser window , how to get it.
 
$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document
 
how to get detects wether a element has just crossed the top most position of the browser
: find  scrollHeight  and substract with the page Height ie 
$(window).height();
code goes below
var scrollHeight = jQuery(window).scrollTop();
// to display the how much you scroll down
   var pos = jQuery("#"+id).show().position();
// find out he position of the element like here we have div
   var pageHeight = jQuery(window).height();
// the page size in height
   var DefaultDivpositon = pageHeight - pos.top ;
// get the location of the div on view port
   var scrollDivpositon = pageHeight - scrollHeight
// this is the top of page-  works as tag. 
 
var diff = scrollDivpositon -DefaultDivpositon;
// this is required for the div is having a height of 50 px ..
 
so it becomes div start way before, the top position of the mouse pointer,
so we need to consider that height 
 
jQuery("#"+id).css("margin-top","-40px");
 
if (diff <=40){ 
                  alert("Invisible");
jQuery("#"+id).css("margin-top",diff-10);
                  //alert("visible");
                  }
                     
var divHt = pos.top+48; 
// added 48 to the top position to counter the additional height
//   of the div from the top
 
 
if( divHt > pageHeight + scrollHeight){
    jQuery("#"+id).css("margin-top","-75px");
// increase the view port added the scrollHeight
   // alert(jQuery("#"+id).css("margin-bottom"));
   // -40 px was the initial top margin again we played with the 
//last code and just made minimal changes to get things done
    }
 
 
The above codes check that if a particular div is hidden on scrolling
if so its just add top marging and pushes it in visible region
but what if we scroll down and face similar situation:
 
if( divTotalHt > pageHeight + scrollHeight){
// increase the view port added the scrollHeight
         jQuery("#"+obj).css("margin-top","-45px");
// -40 px was the initial top margin again we played with the 
last code and just made minimal changes to get things done
    }                            


If popup is too large for the view port just fix it :
             jQuery("#"+obj).css("top",scrollHeight+10);


It worked fine for me.

No comments:

Post a Comment