Scroll to top when checkbox is selected

I just wanted to know how I could get the page scrolled to top when checkbox is selected using jQuery or JavaScript, knowing that there is some Angular JS code in there.

<div class="checkbox-list">
  <div class="checkbox box-collapse-color" ng-repeat="Type in Types">
    <span class="count pull-right">{{Type.count}}</span>
    <input type="checkbox"
           ng-click="addCompanyType(Type.ac)" 
           id="checkbox1-c-{{$index}}" />
    <label class="check" for="checkbox1-c-{{$index}}">
      <span>{{Type.ac}}</span>
    </label>
  </div>
</div>

Thanks in advance.

2 answers

  • answered 2017-06-17 18:52 Max

    I'm not familiar with angular, but this should work:

    if (document.getElementById('checkbox1-c-{{$index}}').checked) {
      $('html, body').animate({
        scrollTop: $('#checkbox1-c-{{$index}}').offset().top
      }, 'slow');
    }
    

    Maybe you have to change the id I used, I'm not sure.

  • answered 2017-06-17 18:52 Alex M

    The easiest way is the following:

    $window.scrollTo(0, 0);
    

    It seems the code should be placed into your addCompanyType function, but I can't say definitely. I'd suggest looking at Angular JS ng-checked directive. Do not forget to inject $window.