Dynamically change class on scroll using VueJs

Struggling to add and remove a class from the header on scroll without success. The class is currently being added multiple times with each scroll, resulting in duplication. How can I ensure the class is only added once and removed when ScrollY < 100?

What mistake am I making in my code implementation?

Check out the Codepen here

<div id="app">
  <v-app>
    <v-content>
      <v-container fluid fill-height class="priceContainer">
      <v-layout row wrap align-center justify-center>
        <v-flex xs12 sm12  text-center>
         <v-toolbar
      :clipped-left="$vuetify.breakpoint.lgAndUp"
      class="elevation-0 "
      fixed
      temporary
      @scroll="handleSCroll"
    >
      <v-toolbar-side-icon @click.stop="drawer = !drawer" ></v-toolbar-side-icon>
      <v-toolbar-title style="width: 300px" class="ml-0 pl-3">
        <span class="PriceLogoTitle hidden-sm-and-up">ELS</span>
        <span class="PriceLogoTitle hidden-sm-and-down">ELS</span>
      </v-toolbar-title>
      <v-spacer></v-spacer>
      <!-- Login button -->
      <v-btn  class="navBtnEnter" flat>Enter <v-icon  right >account_box</v-icon></v-btn>
      <!-- End of login button -->
    </v-toolbar>
        </v-flex>   

      </v-layout>
    </v-container>
    </v-content>
  </v-app>
</div>


.priceContainer{
  background-image: radial-gradient( rgb(3, 237, 245),rgb(0, 126, 131));
  height: 1000px;
}
.theme--light.v-toolbar--bgchange {
    background-color: #009D95;
}

new Vue({
  el: '#app',
  methods:{
      handleSCroll (event) {
        let header = document.querySelector(".v-toolbar");
        if (window.scrollY > 100) {
        console.log(window.scrollY);
        header.className += " v-toolbar--bgchange";          
        }
      }
    },
    created () {
      window.addEventListener('scroll', this.handleSCroll);

    },
    destroyed () {
      window.removeEventListener('scroll', this.handleSCroll);
    } 
})

Answer №1

ElementName is a customizable string, and it allows for multiple instances of the same class without filtering them out. In contrast, classList.add() will not add duplicates, making it useful in scenarios like replacing:

container.className += " custom-class";

with:

container.classList.add("custom-class");

To remove a class, you can use classList.remove("custom-class").

Answer №2

Vue operates reactively, so why manipulate the DOM directly? Let's follow its preferred approach :)

<template lang="pug">
  .main-nav(:class="getMainNavClasses")
    // insert your stylish content here ;)
</template>

<script>
export default {
  name: 'MainMenu',

  data() {
    return {
      scrollingUp: false,
      scrollingDown: false,
      prevScrollpos: window.pageYOffset,
    };
  },

  computed: {
    getMainNavClasses() {
      return {
        'scroll-up': this.scrollingUp,
        'scroll-down': this.scrollingDown,
      };
    },
  },

  methods: {
    scrollNow() {
      const currentScrollPos = window.pageYOffset;

      if (currentScrollPos == 0) {
        this.scrollingUp = false;
        this.scrollingDown = false;
        return;
      }

      if (currentScrollPos < 100) return; // adjust offset as needed

      if (this.prevScrollpos > currentScrollPos) {
        // scrolling up
        this.scrollingDown = false;
        this.scrollingUp = true;
      } else {
        // scrolling down
        this.scrollingUp = false;
        this.scrollingDown = true;
      }

      this.prevScrollpos = currentScrollPos;
    },

    handleScroll() {
      let doScoll;

      window.onscroll = () => {
        clearTimeout(doScoll);
        doScoll = setTimeout(this.scrollNow, 100); // reduce number of scroll events triggered
      };
    },
  },

  created() {
    this.handleScroll();
  },
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery Validation is not functioning correctly

I am facing an issue with implementing jQuery.Validation. I have written a script and included all JS files below, but for some unknown reason, the validation always returns that the form is valid. Below is the JavaScript code I am using: $(document).rea ...

Tips for attaching a React hook to a DOM element generated using a jQuery function

I have a project written in jQuery that I am looking to integrate into my React project. My goal is to send a query to my graphql server when a button is clicked. Within my jQuery code, there is a function that creates multiple elements as shown below: c ...

Crafting a clever smart banner using jquery.smartbanner for Android Firefox users

In order to display smartbanners on my mobile website, I utilize jquery.smartbanner. This implementation has been successful for ios, windows phone, and the default android browser. However, when testing on Firefox for android, the smartbanner is not visib ...

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

The positioning of the Kendo UI window is off-center

I have encountered a problem with the alignment of the Kendo Window. There is a simple fiddle available to demonstrate this issue. Despite having ample space for the Kendo window to show without triggering the browser's vertical scroll bar, the cente ...

Setting up isotope using dynamic JSON data

I've done some searching, but without any luck. My current dilemma involves utilizing the isotope jQuery library to display data in a dynamic manner using a JSON dataset. I've stored the data in a .json file and am reading it in, parsing the info ...

AJAX POST request encountered a 400 Bad Request Error

One of the tasks in my Spring project is to enable data updating in the database upon clicking a specific button. Currently, I have the following code set up: update.jsp : <div class="searchParentOne"> <div class="noticeBlankTwoButtons ...

Adjust the panel size accordingly for smaller screens

My application is utilizing the Spotify API to retrieve names and images. These are then displayed on my webpage within cards/panels in the following format: <div class="col-md-4" v-if="type == 'tracks'" v-for="(track, index) in tracks"> ...

Examining the order in which tabs are navigated

Ensuring correct tab keyboard navigation order within a form is crucial for one of our tests. Query: How can the tab navigation order be verified using protractor? Our current method involves repeating the following steps for each input field in a form ( ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

Track and monitor data modifications in Vue.js

I recently incorporated a Bootstrap Vue Table into my application and wanted to monitor user activity as they navigate through the pages using the pagination feature. Here is where you can find more information on the Bootstrap Vue Table To achieve this, ...

Browser page caching is a way for web browsers to store copies

I am currently investigating how Internet Explorer caches page content (such as input and textarea) in the browsing history. Steps taken: User visits Page1 with a textarea, then navigates to Page2, and returns to Page1 where the textarea data is automati ...

Dynamic Wave Effects with jQuery

I'm interested in developing an interactive animation where waves emanate from a central point and trigger similar waves of varying sizes at outer nodes in a circular pattern. After researching, I came across a few libraries: https://github.com/mbos ...

Using JavaScript, conceal a specific Div by examining the content within another Div

I am attempting to implement some logic using JavaScript. The goal is to hide the "cart-button" div if the innerHTML value of a div with the class "b-format" is set to Audio, otherwise hide the "more-button" div. However, for some reason this functionality ...

ng-bind-html not functioning properly within my situation

Utilizing the ngBindHtml directive in AngularJS to dynamically append HTML, but encountering issues with some area tag attributes not being properly added within the div. As a result, the onclick event in the area tag is not functioning as expected. When ...

Trouble with displaying PHP and AJAX call after switching from JS fetch

Initially, I had a JavaScript function set up to retrieve Wikipedia articles for the chosen country. The code was originally sourced from JS Fiddle and it worked flawlessly. However, I have now been informed that my course mandates all API calls to be made ...

From navigating getElementByID to tackling getElementsByClassName while constructing multiple select elements: a guide

I am facing an issue with accessing multiple select elements that have the same options in Javascript. Despite having the same class, I am unable to retrieve the options using Javascript. When I attempted switching from getElementById to getElementsByClass ...

Mongodb error occurred due to a duplicate key in the collection with the key value set

I need to set up multiple user accounts. The first account creation is successful, but I encounter an error when trying to create a new account: BulkWriteError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.users.$friends. ...

Circular dependencies in ES6 within a React project

After setting up a test project with React Native, I encountered an issue with circular dependencies being reported by Eslint. Despite this warning, the code still functions properly. This is my package.json configuration: ... "dependencies": { "axio ...

Mastering basic DOM manipulation in React with ES6 techniques

My goal is to update the header text when a button is clicked. After trying the code below, I noticed it doesn't work and there are no console errors: class Test extends React.Component { click() { $(".update").val("new value") } ...