You can use jquery to animate the scroll.
using the method animate
you tell the time you want it to take.
For example, setting 500
would take half a second when using milliseconds.
function scroll() {
$('html, body').animate({
scrollTop: $("#p").offset().top
},
500);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button" onclick="scroll()"> myButton </button>
<p> parragraph </p>
<p> parragraph </p>
<p> parragraph </p>
<div style="height: 500px;"></div>
<p> parragraph </p>
<p> parragraph </p>
<p> parragraph </p>
<p id="p"> myParragraph </p>
<div style="height: 1500px;"></div>
For what you ask to be able to pass a unit and move pixels instead of an element, you can say that it moves to the element that you click and a number of extra pixels.
The address would be with +
or -
. Being down and up respectively.
function scroll() {
$('html, body').animate({
scrollTop: $("#button").offset().top + 500
},
500);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button" onclick="scroll()"> myButton </button>
<p> parragraph </p>
<p> parragraph </p>
<p> parragraph </p>
<div style="height: 500px;"></div>
<p> parragraph </p>
<p> parragraph </p>
<p> parragraph </p>
<p id="p"> myParragraph </p>
<div style="height: 1500px;"></div>
Regarding why your smooth
does not work, maybe it's because it only has Firefox support. (see the link compatibility table that you posted)
Without jQuery I found this function recursive. He does it even though the smooth
is questionable ahahha
function scrollTo(duration) {
var element = document.body;
var to = document.getElementById("p").offsetTop;
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo( duration - 10);
}, 10);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button" onclick="scrollTo(600)"> myButton </button>
<p> parragraph </p>
<p> parragraph </p>
<p> parragraph </p>
<div style="height: 500px;"></div>
<p> parragraph </p>
<p> parragraph </p>
<p> parragraph </p>
<p id="p"> myParragraph </p>
<div style="height: 1500px;"></div>