Javascript Scroll Event Adding Class
Hello guys i have a problem with scroll event:
I want to add a class to some link when the section is in the viewport ( is visible ), but the problem is if my scroll position is between the selected range
( in if statement
) everything is ok the class
is added to the link
. But if i continuously scroll to the next section the class is infinite added. How can i only add it once the if statement
is true (scroll position is between the selected range
) ?
// Element position
const attractionSectionPos = Math.floor(ui.attractions_section.getBoundingClientRect().top);
// For intro section
if(attractionSectionPos <= 250 && attractionSectionPos >= -450) {
// Remove the active link if we have more than one
document.querySelectorAll('.active').forEach(link => link.classList.remove('active'));
// Add the class when section is in viewport
document.querySelector('[data-link="attractions"]').classList.add('active');
// Prevent default so we only add the class once
e.preventDefault();
// Remove the class if section is not in viewport
} else { document.querySelector('[data-link="attractions"]').classList.remove('active') }
If i add e.preventDefault()
it gives me a bunch of errors.
E.g: Uncaught TypeError: e.preventDefault is not a function
Answer
I added in the if statement
the following:
!document.querySelector('[data-link="attractions"]').classList.contains('active')
Now everything works smoothly and adds the class
only once when the section
is in the viewport
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM