Javascript Course

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:
- 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

  1. Copy the script code and save it into a JS file named "elmposiz.js", or download it from the link above.
  2. Include the script in your page, AFTER the HTML tags that you want to use with this script.
    <script src="elmposiz.js"></script>
  3. 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>
    
  4. 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.
image in viewport
Here it displays data with: position, size, visible percentage in viewport

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
What attribute makes a radio button or checkbox input selected?
checked="checked" selected="selected" disabled="disabled"
<input type="checkbox" name="a_name" value="value" checked="checked" />
What CSS value scales the background image to the largest size contained within the element?
repeat-x contain linear-gradient
#id {
  background:url("path_to_image.png");
  background-size:contain;
  background-repeat:no-repeat;
}
What operator is used to determine the rest of the division of two numbers?
% * /
var rest8_7 = 8 % 7;
alert(rest8_7);
Indicate the PHP function that rounds a number up to the next highest integer.
floor() ceil() abs()
$nr = ceil(3.5);
echo $nr;        // 4
elmPosiz - Get position, size and visibility in viewport of HTML element

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142070)
  2. Date and Time in ActionScript 3 (10078)
  3. Voting Poll System script PHP-AJAX (8743)
  4. ActionScript 3 Lessons (7369)
  5. Merge Multiple Files, Line by Line (1137)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (73)
  2. The Mastery of Love (17)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (10)
  4. CSS cursor property - Custom Cursors (10)
  5. PHP Unzipper - Extract Zip, Rar Archives (9)