Implementing the sticky class once the user scrolls past a certain element

I am facing an issue in my vue component where I need to add a fixed class to an element when the user scrolls past it. However, the sticky console.log seems to be firing on every scroll instead of only when the element is passed. I also want to remove the class when the element is not passed by.

Below is my component with jQuery code:

<template>
<div id="sticky" style="width:35%; height:85vh; padding:0px 0px; margin:0px 0px 0px auto; background-color:rgb(10,10,10); display:flex; flex-direction:column; position:relative; border:5px solid #9d0000; overflow:hidden; outline:2px solid red;">
        </div>
    </div>
</template>
<!--SCRIPTS-->
<script>
import $ from 'jquery';
export default {
name: 'CARTmodal2',


mounted() {
    console.log(this.$options.name+' component successfully mounted');

    let sticky = $('#sticky'),
    stickyTop = sticky.offset().top,
    scrolled = false,
    $window = $(window);

    /* Bind the scroll Event */
    $window.on('scroll', function(e) {
        scrolled = true;
    });

    let timeout = setInterval(function() {
        /* If the page was scrolled, handle the scroll */
        if (scrolled) {
            scrolled = false;
            if ($window.scrollTop() >= stickyTop) {
                sticky.addClass('fixed');
                console.log("sticky");
            }
            else {
            sticky.removeClass('fixed');
            }
        }
    }, 200);


},



};
</script>
<style scoped>
.fixed{position:fixed; top:0px; left:0px; border:1px slid black;}
</style>

Can anyone point out what might be the problem here?

Answer №1

If you find yourself adding classes externally in the Vue ecosystem, you may run into a problem where Vue replaces the class during an update, disregarding your external changes. In order to work around this issue, utilize an internal conditional statement and the

:class="{'fixedClass':isScrolled}"
parameter to add or remove the class dynamically.

To better understand how to create a fixed header, check out this example that demonstrates how to handle scroll events effectively.

https://www.w3schools.com/howto/howto_js_sticky_header.asp

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

What could be causing the issue of receiving the error message: "Uncaught TypeError: Cannot read property 'Title' of undefined"?

I am currently working on developing an AJAX web application. One of the functions I have is aimed at requesting a JSON object and then utilizing it to refresh the website content. Below is the portion of JavaScript causing an issue (Lines 8 - 16): windo ...

Customize the appearance of alert boxes in ajax requests

Is there a way to customize the default ajax alert box? I currently have code that deletes a user and reloads the current page. It functions properly, but I want to enhance the styling of the alert box that appears before the user is deleted. function d ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

Meteor application: The correct method for fetching a single document from a collection on the client side

Currently in my meteor app, I am saving the unique id of the client within a collection named UserNavigationTracker: { "clientId" : "xxNfxxPGi7tqTbxc4", "currentWizard" : "IntroductionWizard", "currentStep" : "Step-1", "_id" : "ifBJ688upEM ...

Experiencing some unusual shadows in my Three.js project while attempting to add a simple shadow effect to a cube or group of cubes

Trying my hand at implementing shadows in Three.js, even though I am fairly new to JavaScript. My attempts to create a cube with a proper shadow have yielded partial results, as only a portion of the mesh seems to be casting the shadow. https://i.sstatic. ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

An issue arose while attempting to pin a file on IPFS: A TypeError [ERR_INVALID_ARG_TYPE] was encountered, specifying that the argument "url" must be a string data type

Adding the files to another project resulted in an error that I am struggling to understand. When running "node scripts1/runScript.js", the error message received is as follows: Error occurred while pinning file to IPFS: TypeError [ERR_INVALID_ARG_TYPE]: ...

Updating the color of tick marks on checkboxes

I have successfully updated the background color of my checkboxes using a custom function. However, the tick mark on the checkbox now turns black instead of remaining white. How can I keep the tick mark white while changing the background color? Here is t ...

What is the process for filling a table with data sourced from Firebase?

I have successfully used the code below to populate a datatable table with data from a JSON file. However, I am now attempting to populate the table with data from Google's Firebase database. The issue arises because new data pushed into Google's ...

Display an alert when no matches are found in autocomplete suggestions

I am implementing the code below to populate a textbox with data. If I input a, all records starting with a are displayed in the dropdown from the database. However, if I input a value that does not exist in the database, there is no message like "No Recor ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

Making numerous changes to a single field in mongoDB can result in the error message: "Attempting to edit the path 'X' will generate a conflict at 'X'."

Looking to streamline my update operation: private async handleModifiedCategoryImages(data: ModifiedFilesEventData) { this.categoryModel .findByIdAndUpdate(data.resourceId, { $pullAll: { images: data.removedFiles || [] } ...

Ways to verify if the flash plugin has been disabled in the Chrome browser

Is there a way to use JavaScript or jQuery to detect if the flash plugin is blocked in Google Chrome? You can check for a disabled flash plugin using the following code: ((typeof navigator.plugins != "undefined" && typeof navigator.plugins["Shock ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

Issue encountered when attempting to transfer data to MongoDB using custom API

Currently, I have been working on a flutter application that is designed to send data to my custom API built in node js. This API then forwards the data to a MongoDB cluster. While testing the API, everything was functioning correctly and the data was succ ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Tips on how to update the status variable to true depending on the index value

Once I click on the close button, the value immediately changes to "Fruit." How can I achieve this? For instance: Apple close Grapes close Pineapples close Alternatively, is there a way to set the state of "cancel" to true ...

Customize vue.config.js and webpack 4: modify the 'exclude' or 'include' parameters of a rule

I'm trying to customize the exclude/include parameters of a webpack rule in a project created using vue-cli-service. Since it only has a vue.config.js, I can access the configuration using chainWebpack, but modifying the rule directly is proving to be ...

Delay in Ionic list item navigation

As I continue to build my app using "$ ionic start myApp sidemenu" and deploy it directly to Android, I've noticed a significant delay when tapping on the playlist page, such as when selecting "Indie". It feels like there is a 300ms lag before the pag ...

Passing the input value from an HTML file to views is proving to be quite challenging for me

Seeking assistance with creating an add to cart function in Django; encountering an error "POST http://localhost:8000/update_item/ 500 (Internal Server Error)". Any help would be greatly appreciated. Thank you! views.py def updateItem(request): data = js ...