Stephen
Stephen

Reputation: 1183

Vue CSS how to move object across the screen when scrolling

I have a project where I try to hover an element from right to left in the window while scrolling. So when the user is scrolling down the element goes from right to left and when the user is scrolling up it goes from left to right.

I have tried to do this by adding a scroll event listener to the window and then check when this component is visible on the browser(This component is one of multiple components which are shown underneath each other in the application)

If some one knows a better way to achieve this please feel free to comment. I just thought of using the absolute positioning to move the object across the screen.

This is the code I am using at this moment but it doens't want to work. The object doesn't move and stays put.

  data () {
    return {
      position: 0
    }
  },
  created () {
    window.addEventListener('scroll', (event) => {
      this.runOnScroll()
    })
  },
  mounted () {
    const navbar = this.$refs.neonComponent
    this.navbarOffset = navbar.offsetTop
  },
  methods: {
    runOnScroll () {
      if ((this.navbarOffset - 600) < window.pageYOffset) {
        this.position = Math.round((window.pageYOffset - (this.navbarOffset - 600)) / 10)
        this.$refs.neonText.style.right = this.position
      } else {
        if (this.position > 0) this.position = 0
      }
    //   console.log(this.position)
    }
  }
<div ref="neonComponent" class="relative w-full min-h-screen bg-black flex justify-center items-center">
    <div ref="neonText" class="absolute max-w-3xl text-center position-text">
       <h2 class="text-7xl">This is an example text</h2>
    </div>
</div>

Upvotes: 0

Views: 839

Answers (1)

Joshua Angnoe
Joshua Angnoe

Reputation: 1075

Try adding a unit (px, %, vh, vw) to style.right, like so:

        this.$refs.neonText.style.right = this.position + 'px';

Upvotes: 1

Related Questions