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();
}
6
  • Can you not use jQuery? Commented Jun 26, 2015 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. Commented Jun 26, 2015 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. Commented Jun 26, 2015 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. Commented Jun 26, 2015 at 17:02
  • Figure out where you want to scroll to and use scrollTo. Commented Jun 26, 2015 at 18:03

1 Answer 1

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();
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.