Aaron Hartshorn
Aaron Hartshorn

Reputation: 23

Scroll to cursor on click

I'm trying to get the page to smooth scroll so that the cursor is centered vertically once the left mouse button is clicked.

I know how to use an event listener to capture the click location, I'm just unsure of how to calculate the scroll offset to properly center the cursor regardless of the size and position of the scrollbar.

Upvotes: 2

Views: 1007

Answers (1)

Chris
Chris

Reputation: 2806

Something like this can work:

ES6: document.onclick = (e) => window.scroll(0,(e.pageY-window.innerHeight/2))

ES5: document.onclick = function(e) { window.scroll(0,(e.pageY-window.innerHeight/2)) }

pageY should represent the position of the click on the overall page.

We then use window.innerHeight / 2 to get to the middle of the page.

When it comes to smooth scrolling, something like this might work, though I'd probably prefer to use some existing npm package to do that.

function smoothScroll(y, existing) {
    if(!existing && smoothScroll.active) return
    smoothScroll.active = true
    var initialScrollY = window.scrollY
    var scrollDistance = y - window.scrollY
    var scrollAmount = scrollDistance/20
    window.scroll(0, window.scrollY + scrollAmount)
    if(window.scrollY === initialScrollY) {
        smoothScroll.active = false
        return
    }
    setTimeout(function() { smoothScroll(y, true) }, 1)
}

document.onclick = function(e) { 
    smoothScroll(e.pageY-window.innerHeight/2) 
}

Upvotes: 1

Related Questions