Geoff
Geoff

Reputation: 6649

Vuejs scrolled height returns 0

Am using vuejs2 with codeigniter.

I have added the following to the html

<div class="container">
    ...content here
</div>   

In a separate scripts.js i have

script.js

new Vue({
 el: '.container',
 methods:{
    handleScroll:function(event){
      console.log("scrolled to", document.body.scrollTop);
      },
  },
created() {
 window.addEventListener("scroll", this.handleScroll,true);
},
});

Am trying to get the position on y axis that the user has scrolled to but keep on getting 0. What am i missing out. I have included This Codepen

Upvotes: 0

Views: 700

Answers (2)

Demetris Constantinou
Demetris Constantinou

Reputation: 674

You should use the mounted() hook instead of the created().

The created() is executed when your Vue component is created, but this doens't mean the DOM element is there. So mounted() is when your Vue component was created and already mounted to the DOM.

Upvotes: 0

Jacob Goh
Jacob Goh

Reputation: 20845

i think you've misunderstood the usage of scrollTop.

to get the current scroll position, use window.scrollY instead

  console.log("scrolled to", window.scrollY);

Upvotes: 1

Related Questions