[jquery] How do I get the offset().top value of an element without using jQuery?

I'm programming a single-page application using the Angular framework. I'm new to it. I've read this guide to help me understand the fundamental differences between jQuery and Angular and I'd like to follow this guidance as much as possible and NOT use jQuery.

Except that jQuery helps get around some of the browser incompatibilities and provides a useful library of functions, like being able to know the top position of an element from the top of the window, as in $('element').offset().top. No plain Javascript seems to be able to come close without rewriting this function, at which point wouldn't it be a better idea to use a jQuery or jQuery like library?

Specifically, what I'm trying to do is set up a directive that fixes an element in place once the top of it is scrolled to a certain position in the window. Here's what it looks like:

directives.scrollfix = function () {
    return {
        restrict: 'C',
        link: function (scope, element, $window) {

            var $page = angular.element(window)
            var $el   = element[0]
            var elScrollTopOriginal = $($el).offset().top - 40

            $page.bind('scroll', function () {

                var windowScrollTop = $page[0].pageYOffset
                var elScrollTop     = $($el).offset().top

                if ( windowScrollTop > elScrollTop - 40) {
                    elScrollTopOriginal = elScrollTop - 40
                    element.css('position', 'fixed').css('top', '40px').css('margin-left', '3px');
                }
                else if ( windowScrollTop < elScrollTopOriginal) {
                    element.css('position', 'relative').css('top', '0').css('margin-left', '0');
                }
            })

        }
    }
}

If there's a much better way to achieve this in Angular that I'm still just not getting, I'd appreciate the advice.

This question is related to jquery angularjs window offset scrolltop

The answer is


the accepted solution by Patrick Evans doesn't take scrolling into account. i've slightly changed his jsfiddle to demonstrate this:

css: add some random height to make sure we got some space to scroll

body{height:3000px;} 

js: set some scroll position

jQuery(window).scrollTop(100);

as a result the two reported values differ now: http://jsfiddle.net/sNLMe/66/

UPDATE Feb. 14 2015

there is a pull request for jqLite waiting, including its own offset method (taking care of current scroll position). have a look at the source in case you want to implement it yourself: https://github.com/angular/angular.js/pull/3799/files


You can try element[0].scrollTop, in my opinion this solution is faster.

Here you have bigger example - http://cvmlrobotics.blogspot.de/2013/03/angularjs-get-element-offset-position.html


For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):

export class MyComponent implements  OnInit {

constructor(private el: ElementRef) {}

    ngOnInit() {
      //This is the important line you can use in your function in the code
      //-------------------------------------------------------------------------- 
        let offset = this.el.nativeElement.getBoundingClientRect().top;
      //--------------------------------------------------------------------------    

        console.log(offset);
    }

}

Seems you can just use the prop method on the angular element:

var top = $el.prop('offsetTop');

Works for me. Does anyone know any downside to this?


Here is a function that will do it without jQuery:

function getElementOffset(element)
{
    var de = document.documentElement;
    var box = element.getBoundingClientRect();
    var top = box.top + window.pageYOffset - de.clientTop;
    var left = box.left + window.pageXOffset - de.clientLeft;
    return { top: top, left: left };
}

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to window

CMD command to check connected USB devices Get viewport/window height in ReactJS the MySQL service on local computer started and then stopped AngularJS $watch window resize inside directive tkinter: Open a new window with a button prompt window.close() doesn't work - Scripts may close only the windows that were opened by it Send parameter to Bootstrap modal window? How do I insert a JPEG image into a python Tkinter window? Installing Python 2.7 on Windows 8 How do I get the offset().top value of an element without using jQuery?

Examples related to offset

Laravel Eloquent limit and offset Get div's offsetTop positions in React Bootstrap 3: Offset isn't working? How to fix Warning Illegal string offset in PHP Pagination using MySQL LIMIT, OFFSET How do I get the offset().top value of an element without using jQuery? Get position/offset of element relative to a parent container? offsetting an html anchor to adjust for fixed header Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge? Can you control how an SVG's stroke-width is drawn?

Examples related to scrolltop

Angular 5 Scroll to top on every Route click How do I get the offset().top value of an element without using jQuery? jQuery .scrollTop(); + animation Run ScrollTop with offset of element by ID $(window).scrollTop() vs. $(document).scrollTop() How to scroll to top of a div using jQuery?