Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function to get the current viewport?

Tags:

jquery

I found this one:

getViewport = function () {
  var m = document.compatMode == 'CSS1Compat';
  return {
    l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
    t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
    w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
    h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
  };
};

But does jQuery have a built in function for this?

like image 865
Alex Avatar asked Apr 25 '12 22:04

Alex


1 Answers

While there's not a single built-in function, the function itself can be simplified with jQuery functions:

getViewport = function() {
    var $w = $(window);
    return {
        l: $w.scrollLeft(),
        t: $w.scrollTop(),
        w: $w.width(),
        h: $w.height()
    }
}

Tested it out here: http://jsfiddle.net/naLLa/

You may also find this plug-in of interest, which adds viewport-based selectors: http://www.appelsiini.net/projects/viewport

like image 187
Dan A. Avatar answered Nov 03 '22 02:11

Dan A.