Always return to the top of the screen when clicking on links from a SPA with Angular.Js

0

I have an angled project, of which I define my views with $routeProvider and call the appropriate controllers, and use <ng-view></ng-view> to display them on my site.

There are a few pages, but scrollbars, and clicking a link that switches from one view to another <a ng-href="#">#

asked by anonymous 09.02.2017 / 18:02

1 answer

1

Using Angular only, I found the ngView documentation , which recommends using:

<div class="ng-view" autoscroll="true"></div>

But if you want to use a bit of jQuery do the following, add the Scroll Function to all <a> using .delegate() so jQuery even matches the <a> dynamically created by AngularJS:

$("body").delegate("a", "click", function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
});
#altura {
  height: 1000px;
  width: 100%;
  background: #EEE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="altura"></div>
<a>Todos os Links</a>

And if you want to do it using pure JS only:

var Anchors = document.getElementsByTagName("a");

for (var i = 0; i < Anchors.length ; i++) {
    Anchors[i].addEventListener("click", 
        function() {
            document.body.scrollTop = 0;
        }, 
        false);
}
#altura {
  height: 1000px;
  width: 100%;
  background: #EEE;
}
<div id="altura"></div>
<a>Todos os Links</a>

Another solution using Pure JS:

#altura {
  height: 1000px;
  width: 100%;
  background: #EEE;
}
<div id="altura"></div>
<a onclick="location.href='#altura'">Todos os Links</a>
    
09.02.2017 / 18:07