AngularJS Scroll to a Specific Element using Anchorscroll

By Hardik Savani October 20, 2023 Category : Bootstrap jQuery Angular

Sometimes, we require to scroll on specific element or div on angularjs application like scroll for go on specific comment, scroll on specific table row it. However we can do it using anchorscroll in angularjs application.

anchorscroll() will help to scroll on specific "anchor" div id. anchorscroll() is provided by angularjs. We can use it simply. We don't require to write login on code jquery, because it is easy to do using anchorscroll(). $anchorScroll will use with $location variable hash.

I gave you full example of how to scroll on specific element on angularjs page, We can use simple as bellow code:

$scope.gotoDiv = function(x) {

var newHash = 'anchor' + x;

if ($location.hash() !== newHash) {

$location.hash('anchor' + x);

} else {

$anchorScroll();

}

};

Now we are going to show full example of $anchorScroll, you can also see demo for this example. You can copy bellow code and run in your machine, So let's see bellow code:

index.html

<!DOCTYPE html>

<html>

<head>

<title>Angular scroll to a specific element</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<style type="text/css">

.scroll-div {

height: 100px;

overflow: scroll;

margin-top: 50px;

}

.anchor {

border: 2px dashed red;

padding: 10px 10px 200px 10px;

}

.my-fixed-header {

background-color: rgba(0, 0, 0, 0.2);

height: 50px;

position: fixed;

top: 0; left: 0; right: 0;

}

.my-fixed-header > a {

display: inline-block;

margin: 5px 15px;

}

</style>

</head>

<body>


<div ng-app="mainApp" ng-controller="myController" id="mainController" class="container">


<div class="my-fixed-header">

<a href="" ng-click="gotoDiv(x)" ng-repeat="x in [1,2,3,4,5]">

Go to Div {{x}}

</a>

</div>


<div class="scroll-div">

<div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">

Div {{x}} of 5 Div

</div>

</div>


</div>


<script type="text/javascript">

var app = angular.module("mainApp", []);


app.controller('myController', function($scope, $anchorScroll, $location) {


$scope.gotoDiv = function(x) {

var newHash = 'anchor' + x;

if ($location.hash() !== newHash) {

$location.hash('anchor' + x);

} else {

$anchorScroll();

}

};


});

</script>


</body>

</html>

I hope it can help you...

Shares