Vanilla JavaScript to get basic webpage document information

I recommend old school vanilla JS when you just want the bare minimum information and light load for developing popup screens etc. The below code I sometime use to get document info the old dirty way without having to load a heavy JavaScript library.

The getDocInfo function collects all the variable document information and returns it as a object. You can then use it as you wish over and over again.

function getDocInfo(){
    var doc = {};
    var body = window.document.body;
    var document = window.document;
    var w = window.innerWidth || document.documentElement.clientWidth || body.clientWidth;
    var h = window.innerHeight || document.documentElement.clientHeight || body.clientHeight;
    doc.clientHeight = h;
    doc.clientWidth = w;
    doc.scrollTop = document.scrollingElement.scrollTop || 0;
    doc.scrollLeft = document.scrollingElement.scrollLeft || 0;
    doc.docHeight = body.clientHeight;
    doc.docWidth = body.clientWidth;
    doc.scrollYBarWidth = (doc.clientWidth - doc.docWidth);
    return doc;
}

For example, calling the function and listing information based on window document events like onload or onscroll. 

window.onload = function(){
    console.log(getDocInfo());
}
window.onscroll = function(){
    console.log(getDocInfo().scrollTop);
}
window.onresize = function(){
    console.log(getDocInfo().
clientWidth);
}


Comments

Popular posts from this blog

Build 6 is here

An example of chaining jQuery Ajax request callbacks

Creating hashtag hyperlinks on the fly for your website