Div offsetHeight and other values are different on server vs local

First of all I’ll apologize for my english.

So my goal is to create an anchor link menu with Nuxt.js which scrolls to the page section the user has clicked and now I have few different ways of doing it but I’m not sure which is the "correct one".

Option 1:

I created a menu which gets the offsetTop of the section div to know how far to scroll when the user clicks a link in the menu, but the problem I’m having with this is that few of the div’s values such as offsetHeight and offsetTop change when I push the project to the server and I’m not sure what is causing it. For the result of this the link scrolls to the wrong place and does not work properly.

Here I get the values and set them to the Vuex state:

    elements.forEach((element) => {
            var name = element.name
            var el = element.el
            var posTop = el.offsetTop - bodyScrollTop
            var elementHeight = el.offsetHeight
            var posBottom = posTop + elementHeight
            this.$store.state.windows.forEach((window) => {
              if(window.id == name) {
                window.posTop = posTop
                window.posBottom = posBottom
                console.log('PosTop', window.id, window.posTop)
                console.log('PosBottom', window.id, window.posBottom)

I use window.scrollTo() to scroll to the section:

    if (process.client) {
          top: position, 
          left: 0, 
          behavior: 'smooth'

Option 2:

The second way I tried to make it work was with anchor links and I got it to scroll to the right section when clicking a link in the menu but now the problem is that I need to change the hash is the url when the user scrolls to a section. I tried to change the url with this.$router.push({path: element.hash}). The url changes when the user entries the section but the problem is that every time $router.push runs, the scrolling experience becomes very bad because it tries to scroll back to the section while the user is scrolling down to a new section.

Now I’m jumping between these two and don’t know which one would be the better option to invest my time in.

Thank you in advance!

Source: JavaSript – Stack Overflow

November 28, 2021
Category : News
Tags: javascript | nuxt.js | offsetheight | Vue.js | vuex

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.