elmPosiz is a JS script that gets some
useful data of a HTML element in page, like:
top and left position, width and height size, and percentage visible in viewport.
So, this script can be used to
check if a Div, image or other html element is in viewport, also, to get its top/left position and size.
It works on tablets, mobile and desktop devices; in all major browsers: Chrome, Mozilla Firefox, Internet Explorer, Opera, Safary.
• To download the script, click on this link:
Download elmPosiz (5 KB)
Script code - click on the code to select it
//JavaScript code to get some parameters of a html element in page - https://coursesweb.net/javascript/
// slc = CSS selector that represents the element
function elmPosiz(slc){
var me = this;
var elm = document.querySelector(slc); //element represented by slc
me.win_w, me.win_h; //window width and height
me.top, me.left, me.width, me.height; //position and size of elm
me.min_visible =50; //minimum percentage for elm visible in viewport
me.in_view; //true if elm in viewport; else false
me.visibleX; //percentage of elm width visible in viewport, on X axis
me.visibleY; //percentage of elm height visible in viewport, on Y axis
me.listen; //for function executed on window resize and scrolling page
//sets window size {w:width, h:height}
var winSize = function(){
var re ={};
if(self.innerHeight){
re.h = self.innerHeight;
re.w = self.innerWidth;
} else if(document.documentElement && document.documentElement.clientHeight){
re.h = document.documentElement.clientHeight;
re.w = document.documentElement.Width;
} else if(document.body){
re.h = document.body.clientHeight;
re.w = document.body.clientWidth;
}
me.win_w=re.w; me.win_h=re.h;
}
//sets position and size of elm: {x:left, y:top, w:width, h:height}
function posSize(elm){
function getOffset(object,offset){if(!object)return;offset.x+=object.offsetLeft;offset.y+=object.offsetTop;getOffset(object.offsetParent,offset);}
function getScrolled(object,scrolled){if(!object)return;scrolled.x+=object.scrollLeft;scrolled.y+=object.scrollTop;if(object.tagName.toLowerCase()!='html')getScrolled(object.parentNode,scrolled);}
function getZoomFactor(){var factor=1;if(document.body.getBoundingClientRect){var rect=document.body.getBoundingClientRect();var physicalW=rect.right-rect.left;var logicalW=document.body.offsetWidth;factor=Math.round((physicalW/logicalW)*100)/100;}
return factor;}
var re={x:0,y:0,w:0,h:0};if(elm.getBoundingClientRect){var rect=elm.getBoundingClientRect();var x=rect.left;var y=rect.top;var w=rect.right-rect.left;var h=rect.bottom-rect.top;if(navigator.appName.toLowerCase()=='microsoft internet explorer'){x-=document.documentElement.clientLeft;y-=document.documentElement.clientTop;var zoomFactor=getZoomFactor();if(zoomFactor!=1){x=Math.round(x/zoomFactor);y=Math.round(y/zoomFactor);w=Math.round(w/zoomFactor);h=Math.round(h/zoomFactor);}}
re={x:Math.round(x),y:Math.round(y),w:Math.round(w),h:Math.round(h)};}
else{var offset={x:0,y:0};getOffset(elm,offset);var scrolled={x:0,y:0};getScrolled(elm.parentNode,scrolled);var x=offset.x-scrolled.x;var y=offset.y-scrolled.y;var w=elm.offsetWidth;var h=elm.offsetHeight;re={x:Math.round(x),y:Math.round(y),w:Math.round(w),h:Math.round(h)};}
me.top=re.y; me.left=re.x; me.width=re.w; me.height=re.h;
}
//sets the visibleX property; the visible percent of elm width in viewport
var getVisibleX = function(){
if(me.left >=0) var re = Math.max(0, Math.min(100, (me.win_w - me.left)*100/me.width));
else var re = Math.max(0, Math.min(100, (me.width + me.left)*100/me.width));
me.visibleX = re.toFixed(2);
}
//sets the visibleY property; the visible percent of elm height in viewport
var getVisibleY = function(){
if(me.top >=0) var re = Math.max(0, Math.min(100, (me.win_h - me.top)*100/me.height));
else var re = Math.max(0, Math.min(100, (me.height + me.top)*100/me.height));
me.visibleY = re.toFixed(2);
}
//sets the in_view property - true if elm is in viewport with minimum percentage; else false
var setInView = function(elm){
me.in_view = (me.visibleY >=me.min_visible && me.visibleX >=me.min_visible) ?true :false;
}
//calls functions that set properties
function construct(){
winSize();
posSize(elm);
getVisibleX();
getVisibleY();
setInView(elm);
if(typeof me.listen=='function') me.listen();
}
if(elm){
construct();
// when Resize browser, re-set properties
window.addEventListener('resize', construct);
// when scrolling page, re-set properties
window.addEventListener('scroll', construct);
//execute listen after 250 miliseconds if it is a function
window.setTimeout(function(){ if(typeof me.listen=='function') me.listen();}, 250);
}
}
The JavaScript object created with elmPosiz() has these properties:
- top - top position of the element in page (in pixels).
- left - left position of the element in page (in pixels).
- width - element width (in pixels)
- height - element height (in pixels)
- listen - this property is used to pass a function that is executed every time these parameters are actualised; when window is resized or page scrolls.
- min_visible - you can use this property to set the minimum percentage that considers the element visible in viewport. Default 50.
- in_view - boolean value, true if the element is in viewport (according to min_visible value), or false.
- visibleX - a number with the current percentage of the element's width visible in viewport, on horizontal axis.
- visibleY - a number with the current percentage of the element's height visible in viewport, on vertical axis.
- win_h - browser window height.
- win_w - browser window width.
- These parameters are actualised every time the window is resized or the page scrolls, so you can detect when an element is entering or exits viewport.
Usage
- Copy the script code and save it into a JS file named "elmposiz.js", or download it from the link above.
- Include the script in your page, AFTER the HTML tags that you want to use with this script.
<script src="elmposiz.js"></script>
- Create an object instance with the elmPosiz() function, passing the CSS selector that represents the HTML element, usually an ID.
<script>
var ob_nm = new elmPosiz('#the_id');
</script>
- Now you can use the "ob_nm" object properties, presented above.
- Here is a simple example:
<div id="dv1">Div content</div>
<script src="elmposiz.js"></script>
<script>
//create object with the elmPosiz() for #dv1
var ob_dv1 = new elmPosiz('#dv1');
//check if #dv1 is minimum 50% visible in viewport
//shows an alert message with top/left position
var dv1_vi = ob_dv1.in_view ?'Visible in viewport' :'Not 50% visible in viewport';
alert('Top: '+ob_dv1.top+' / Left: '+ob_dv1.left+'\n'+dv1_vi);
</script>
- Another example. We set a function to the "listen" property to check when the Div exits viewport, and shows in console the visible percentage.
<div id="dv1">Div content</div>
<script src="elmposiz.js"></script>
<script>
//create object with the elmPosiz() for #dv1
var ob_dv1 = new elmPosiz('#dv1');
//change minimum percentage to 70% for #dv1 to be considered visible in viewport
ob_dv1.min_visible = 70;
//set a function to the listen property to check #dv1 visibility in viewport,
//and shows in console the visible percentage
ob_dv1.listen = function(){
if(!ob_dv1.in_view) console.log('Elm not 70% in viewport, visible: ', ob_dv1.visibleY);
}
</script>
Example with an image:
<div class="apare">
<img src='image.jpg' alt='image' id='ex_im1'/>
<div id="im1_data">Here it displays data with: position, size, visible percentage in viewport</div>
</div>
<script src="elmposiz.js"></script>
<script>
//function to be passed to "listen" property; adds data in #im1_data
function showElmdata(){
im1_data.innerHTML ='Visible in Viewport: '+ob_im1.visibleY+' %<br>Top: '+ob_im1.top+'<br>Left: '+ob_im1.left+'<br>Width: '+ob_im1.width+'<br>Height: '+ob_im1.height;
}
// object of html where data will be displayed
var im1_data = document.getElementById('im1_data');
//create object with the elmPosiz() for #dv1
var ob_im1 = new elmPosiz('#ex_im1');
//add showElmdata to listen property, executed when the page scrolls or window resizes
ob_im1.listen = showElmdata;
</script>
- Demo, scroll the page or resize the window. Notice the parameters of this image in page.
Here it displays data with: position, size, visible percentage in viewport