K-Infected K-Infected - 3 months ago 18
jQuery Question

AngularJs - smooth scroll to a div

I am building a website using AngularJS and I am quite new to it. But I am familiar with jQuery. In my website I want to smooth scroll to a specific

<div>
on click of a button. I have a code for this in jQuery. But I don't know how to write the same code in AngularJS. Can anyone tell me how to write this same code in AngularJS?

Here is the Snippet



$('#todivone').click(function () {
$('html, body').animate({
scrollTop: $('#divone').offset().top
}, 'slow');
});
$('#todivtwo').click(function () {
$('html, body').animate({
scrollTop: $('#divtwo').offset().top
}, 'slow');
});
$('#todivthree').click(function () {
$('html, body').animate({
scrollTop: $('#divthree').offset().top
}, 'slow');
});

div {height: 900px; border:2px solid #333; padding:10px; margin: 0px;}
button {position: fixed; margin-top: 50px;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="todivtwo">GOTO DIV 2</button>
<br>
<button id="todivthree">GOTO DIV 3</button>
<br>
<button id="todivone">BACK TO DIV 1</button>
<br>
<div id="divone">DIV CONTENT 1</div>
<div id="divtwo">DIV CONTENT 2</div>
<div id="divthree">DIV CONTENT 3</div>




Answer

Try it with ng-click

    <button id="divone" ng-click="goToDiv(1)">DIV CONTENT 1</button>
    <button id="divtwo" ng-click="goToDiv(2)">DIV CONTENT 2</button>
    <button id="divthree" ng-click="goToDiv(3)">DIV CONTENT 3</button>

In the controller:

$scope.goToDiv= function(a){
if(a==1){
 $('html, body').animate({
        scrollTop: $('#divone').offset().top
    }, 'slow');
}
if(a==2){
$('html, body').animate({
        scrollTop: $('#divtwo').offset().top
    }, 'slow');
}
if(a==3){
$('html, body').animate({
        scrollTop: $('#divthree').offset().top
    }, 'slow');
}
}
Comments