How to scroll to an element



  • Hello, I have been reading the scroll documentation for almost an hour and I’m still unable to understand it.
    What I want to do is, when someone clicks on one button I want to scroll to certain dom element, which is out of view.
    I tried using refs and the scroll utils, but they don’t work at all, nothing happens. Checking the console I can see that the getScrollPosition function always returns 0, and therefore no navigation happens.
    If you can tell me a nice way to simply scroll to certain element I will be very grateful. Also I really think that documentation should be revised, they seem wrong.

    Thanks in advance



  • Funny, the same question was asked in Discord yesterday and we wanted to upgrade the docs for it.
    Here is the solution we came up with

    import { scroll } from 'quasar'
    const { getScrollTarget, setScrollPosition } = scroll
    
    export default {
      methods: {
        handleScroll () {
          const ele = document.getElementById('test') // You need to get your element here
          const target = getScrollTarget(ele)
          const offset = ele.offsetTop - ele.scrollHeight
          const duration = 1000
          setScrollPosition(target, offset, duration)
        }
      }
    }
    


  • Hello @a47ae , thank you for your response.
    The part about getting the element was pretty simple, I was just using references. However, the animation part was more difficult.
    May I ask why are you calculating the offset that way ? In my case the element it’s out of view, and its size is close to the size of the window. Using your code I get an offset of 18, which is barely noticeable. However, if I just use ele.offsetTop directly the element just scrolls into view perfectly, sho hence my question, why are you calculating the offset that way ?

    Another thing I am unable to understand is how the (and why) the target is decided. In my case, I don’t have any element with the scroll class, so window is used. Using window and calculating the offset as I said, works perfectly. On the contrary, if I add the scroll class to the current page, then the scroll does not happen, no matter how you calculate the offset. All this stuff is very confusing.

    Regards.


  • Admin

    @danielo515 You don’t need anything from Quasar for this. Just think in plain JS terms only. The getScrollTarget() is a helper which looks for the closest DOM element with scroll CSS class or else returns the window object.


Log in to reply
 

Looks like your connection to Quasar Framework was lost, please wait while we try to reconnect.