Implementing a Fixed Navbar in VueJS on Scroll

I am seeking help with creating a Fixed Navbar on Scrolling using Vue.js.

I initially wrote some jQuery code for this functionality, but now I want to transition it to Vue.js.

The updated code can be found in a file named navbar.js.

Previous jQuery CODE:

$(document).ready(function fixedHeader() {

    var windows = $(window);
    var screenSize = windows.width();
    var sticky = $('#f-navbar');
    var $html = $('html');
    var $body = $('body');

    windows.on('scroll', function () {
        var scroll = windows.scrollTop();
        var headerHeight = sticky.height();

        if (screenSize >= 320) {
            if (scroll < headerHeight) {
                sticky.removeClass('is-sticky');
            } else {
                sticky.addClass('is-sticky');
            }
        }
    });
});

Updated Vue JS Code:

const navbar = new Vue({
    el: '#f-navbar',
    data: function fixedHeader() {
        return {
            stickyNavbar: {
                isSticky: false
            }
        }
    },
    mounted() {

    },
    methods: {
        handleScrolling () {

        }
    }
});

HTML Markup:

<nav id="f-navbar" class="navbar navbar-custom navbar-expand-lg navbar-light bg-white"
     v-bind:class="stickyNavbar"></nav>

Answer №1

When $(document).ready is utilized, it functions similarly to Vue's mounted hook but specifically applies to Component.

In your Navbar.vue file within the <script> section:

mounted() {
    window.addEventListener('resize', this.getWindowWidth);
  },
data() {
    return {
      screenSize: 0,
    };
  },
  methods: {
    getWindowWidth() {
      this.screenSize= window.innerWidth;
    },
  },

Within the template section of your NavBar component,

you should assign the :class based on certain conditions:

<nav :class="{'is-sticky': screenSize == 320}">

UPDATE: The is-sticky class will only be visible when the scroll position equals 320 in the window's width size.

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

Adjust the position by changing the left property during dragging

Whenever I try to update the left property of a ul element while dragging, it unexpectedly jumps to -1980 as soon as the drag action begins. $('#draggable').on('drag', function() { var start = 0; var end = 2000; while (st ...

The transparent DIV/waiting message may not be displayed in IE10

Here is a DIV container that serves as a transparent background with a loading message. This is the HTML code for the DIV container: <div id="generatingexcel" style="display:none; position: fixed; width: 100%;height: 100%; z-index: 999; top: 0; left: ...

Is JSP being double-dipped via an Ajax request?

I'm encountering an issue with a JSP1 that is using Ajax to pass a variable to another JSP2. It seems like JSP2 is being loaded twice, and I can't figure out why. When I check my app console log, I see the following: my_id = 77An2J my_id = null ...

Is the JQuery Ajax serialize function failing to function properly?

I am having an issue when trying to submit a form using jQuery. For some reason, the form always appears empty. Within the form, I have set up a while loop with various input fields containing different names. My goal is to display the values of these inpu ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Styling an input button to look like a link in Firefox and Internet Explorer

I'm currently using CSS to give my input button the appearance of a link. Here's how I've styled it: input#linkLike { background: none; border: none; cursor: pointer; margin: 0; padding: 0; text-decoration: none; ...

Switch website address without redirecting via JavaScript

I am seeking information on how to update the URL without a full page reload, similar to the functionality seen on this website . When clicking on tabs, the URL changes seamlessly without refreshing the entire page. While some sources suggest that this m ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

How to Dynamically Load SVGs in Angular 10 Without Using IMG or OBJECT Elements

I have been exploring a more streamlined method for loading SVG files without relying on IMG or OBJECT tags, as it limits my ability to control fill colors through external CSS. While using inline SVG seems like the best option, managing numerous component ...

The issue with the sticky menu not functioning properly may be due to the use

Hey there, I'm facing an issue with the Navbar Menu (White Bar) on my website. It is working perfectly fine and sticking to the top as expected. However, the problem arises when I click on the Menu - the Sticky class stops working. Upon investigating, ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

Creating a split-view menu in WinJS: A step-by-step guide

I'm attempting to create a versatile app using JavaScript. I followed a tutorial on the MSDN website, but for some reason, the "nav-commands" class isn't displaying when the splitview is opened. I have set closedDisplayMode = 'none'. & ...

What steps should be taken in VUEjs if the API response is null?

There's a method in my code that retrieves a token from an API: let { Token } = await API.getToken({ postId: postId }) if(){} Whenever the token is null, I receive a warning in the console saying "Cannot read property 'Token' ...

Understanding the concept of for loops in JavaScript and incorporating them in CSS styling

Hello there! I initially used this code to draw 12 lines, but now I am looking to incorporate a for loop and implement it in CSS. Can someone please guide me on how to proceed? <!DOCTYPE html> <html> <head> <style> #straigh ...

Ways to identify when a modal window is being closed in the angular-ui $modal component

I am currently utilizing the $modal from angular-ui to generate a modal window. Below is the code snippet for creating the modal: this.show = function (customModalDefaults, customModalOptions, extraScopeVar) { //Create temporary objects to work with s ...

Using Jquery to monitor input field modifications following a background ajax refresh

I am facing a challenge with my two JQuery functions. The first function executes an ajax load based on the user's selection from a drop-down menu, and then updates an input field according to the data returned. This function is working correctly. // ...

Tips for locating the highest number in JavaScript

I'm having trouble with my code where the first number, even if it's the largest, is not displaying as such. Instead, it shows the second largest number. Even when following suggestions, I encountered an issue where if the numbers are entered as ...

Having trouble with the carousel previous and next buttons being blocked by boxes in Bootstrap 5, causing them to not work properly

I am currently working on a tutorial project for my class that involves implementing bootstrap5 carousel with previous and next sliding buttons. However, when I try to run the code, I am facing an issue where there are boxes appearing over the buttons an ...

Using a background image in a React component

Currently, I am working on a webpage and facing an issue while trying to set a background image for a Material UI element using the background-image CSS property. Despite researching online for solutions, I am unable to make the image appear. P.S.1: I eve ...

The MVC Partial View triggers the Document.Ready() function using jquery.get() instead of Ajax.BeginForm

After discovering that MVC's Ajax.BeginForm was behaving strangely when returning a view, I realized that the document ready bindings were lost. It seemed that document ready was not being executed as expected. While experimenting with a jQuery get m ...