We can use jquery to scroll our page to any specific element.
Some key things to keep in mind before that are:
- The target element should be present on the page
- It’s better to include the target element as an id
- There should be only one id for that element on the page
Note that we can scroll to multiple locations too, using same target selector (for example a class instead of id). This would be helpful in case where you want to cycle through multiple locations on repeatedly clicking button for example.
How to scroll to a page element on clicking another element using jquery
Change the trigger and target element selector in this code to match yours.
Note that we can do this without animation too (see the next code block under this)
<script>
// "target" is the id of target element
// "trigger" is the id of triggering element
$(function () {
$("#trigger").on("click", function () {
$('html, body').animate({
scrollTop: $("#target").offset().top
}, 2000);
return false;
})
});
</script>
Understanding this jquery code:
- The offset() gives us an object containing both top and left offsets
- So we use the .top after offset() to get the value of top offset only
- The 2000 on line 8 is not required. However, when present, it defines the duration of this animation in milliseconds. So 2000 means 2 seconds.
How to scroll to an element without animate
If you simply want to jump to the element without scroll animation, use this code (modified from the code above, so similar explanation):
<script>
// "target" is the id of target element
// "trigger" is the id of triggering element
$(function () {
$("#trigger").on("click", function () {
$("body").scrollTop($("#target").offset().top)
})
});
</script>
We can achieve this using vanilla javascript too, but for now lets use jquery version.
Please let me know if you need any help in modifying it or understanding it.