Home > OS >  Javascript eventListener of scroll dosen't work
Javascript eventListener of scroll dosen't work

Time:08-11

I added an eventListener of 'scroll' to an element and it's not working.

If I use onscroll="myFunction()" on the p tag and then I access it, it works just fine.

Where is the problem?

Thanks!

const myDiv = document.querySelector('#hScroll')
const customInfo = document.querySelector('#customInfo')

console.log(customInfo)

customInfo.addEventListener('scroll', () => {
    console.log('yup');
})
<div id="hScroll" >
  <p id="customInfo" >Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
  </p>
</div>

CodePudding user response:

because no scrolling events, occurs in your element (which is P)

try this code and you will findout what I mean.

const myDiv = document.querySelector('#hScroll')
const customInfo = document.querySelector('#customInfo')

console.log(customInfo)

customInfo.addEventListener('scroll', () => {
    console.log('yup');
})
<p id="customInfo"  style="width:60px; height:60px; overflow-y:auto">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown
  </p>

CodePudding user response:

The problem was that I'm using VUE js and my HTML tag was defined into the div with the id of #app and aparently VUE js, somehow, deactivates the addEventListener if you do like this.

SOLUTION

I put my javascript into VUE mounted() and it works.

CodePudding user response:

The callback function has to take an event parameter.

customInfo.addEventListener('scroll', (ev) => {
    console.log('yup');
})
  • Related