1

I am working on an application built in AngularJS. One requirement that has been passed to me is that when a form is invalid and the user clicks submit, the window should scroll the first invalid element into view.

This is pretty easily accomplished using element.scrollIntoView() but I need to set an offset. You see, the top of the page has a header that 'fades into' the rest of the page. See the image below.

enter image description here

So i'm left to try to figure out some method of offsetting. I have found a bunch of examples but i'm not finding exactly what i'm looking for.

Here is my current code (

var visibleInvalids = angular.element.find('.ng-invalid:visible');
if (angular.isDefined(visibleInvalids)){
    // if we find one, set focus and anchor
    visibleInvalids[0].scrollIntoView(true);

    visibleInvalids[0].focus();
}
CarComp
  • 1,929
  • 1
  • 21
  • 47
  • Can you not use jQuery? – Zack Tanner Jun 26 '15 at 16:50
  • I really shouldn't, since its an AngularJS app. I'm skating the edge moving the page as it is, since its a direct dom manipulation from a controller. Yuck. – CarComp Jun 26 '15 at 16:51
  • I'd be curious to see the angular friendly implementation of this (in a directive). I do something similar on a site, but alas it uses jQuery. – Zack Tanner Jun 26 '15 at 16:59
  • What i proposed *might* be able to go into a directive. I'm not even accepting it yet. I want to get some votes and comments first. – CarComp Jun 26 '15 at 17:02
  • Figure out where you want to scroll to and use `scrollTo`. –  Jun 26 '15 at 18:03
  • Use scrollTo( x-dimesion ,y-dimension) on the container which use want to scroll. – Swaprks Jun 26 '15 at 19:06

1 Answers1

0

Proposed answer to my own question. Inject $anchorScroll and use that, but i'm open to ideas...

  var visibleInvalids = angular.element.find('.ng-invalid:visible');

  if (angular.isDefined(visibleInvalids)){
    // if we find one, set focus and anchor

    // Offset is used to keep items 'below' that fade-in header.
    $anchorScroll.yOffset = 200;
    if (visibleInvalids[0].id) {
      $anchorScroll($location.hash(visibleInvalids[0].id));  
    }

    visibleInvalids[0].focus();
  }
CarComp
  • 1,929
  • 1
  • 21
  • 47