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

What are some effective ways to integrate jquery, ajax, and mysql technology in combination?

I'm encountering an issue while trying to integrate jQuery and AJAX into my code. I attempted to do so but was unsuccessful. Below is my jQuery code: $(document).ready(function () { $('#btnGOlustur_Click').click(function () { v ...

``I am facing an issue where the jQuery html() function is not properly

I am struggling with a div <div id="box-loading-txt">txt</div> Despite my efforts, this jQuery code doesn't seem to be working properly. The content in the div always ends up showing as "text B text B text B" even on the initial html() ...

Is it possible to create a translucent glass floating box over HTML elements, similar to the frosted glass effect seen in iOS7?

Creating an overlapping div with a frosted glass effect typically requires using an image background (like ). I am interested in having a floating div (position:fixed) that can apply a frosted glass effect over any content below it, whether it be an image ...

How can you efficiently send JSON data from Ajax to a Servlet in a Java environment?

I am encountering a perplexing issue with sending data from my jQuery script to a servlet using AJAX. The strange part is that when I set the contentType to application/json, all values on the server side turn out to be null. However, if I remove it, the s ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

The updates made to a variable within an ajax request are not immediately reflected after the request has been completed

My global variable is not displaying the expected result: function checkLiveRdv(salle, jour, dateus, heure) { var resu; var urlaction = myUrl; $.ajax({ type: "POST", dataType: "json", url: urlaction, data: myDatas, suc ...

Images that have been resized on Android appear blurry when viewed on the second page

Customizing the Toolbar: #main_bar { background: url(../images/logo.jpg) 99% 50% no-repeat; background-size: auto 80%; } The original size of logo.jpg is 220x266px The toolbar has a fixed height of 46px Therefore, the background image appears t ...

Is there a way to verify if a button is disabled with Vue Test Utils?

I'm currently facing an issue while testing a Vue component regarding the disabled state of a button. How can I retrieve and verify a button's disabled status during my tests? So far, I have attempted to use .attributes(), but it seems that this ...

Adding rows to a database can be done by utilizing a dynamic form that consists of both repeatable and unique fields

Here is my follow-up post addressing the issue I previously encountered. Initially, I erroneously used mysql instead of mysqli, but I have now made the necessary updates based on recommendations. I have a form that contains variable sets of fields (rangin ...

Executing an on-click event on a button in PHP

I've been developing a learning site that involves teachers, students, and different subjects. To organize the registration process, I decided to separate the teacher and student registration pages since they input data into different tables in the da ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Ways to eliminate the dotted line from the image map in Internet Explorer 11

Below you will find the code I am working with: <img alt="Testing 2015" border="0" src="images/Test-2015.jpg" usemap="#Map" /> <p><map name="Map"><area coords="790,100,653,135" href="http://www.google.com/" shape="rect" style="cursor ...

Creating a JQuery Dialog Box Integrated with DataTable()

I need some assistance with a problem I'm encountering while using Asp.net and JQuery UI 1.9.2. On my form, I have a textbox and a search button. Upon clicking the button, I query the database on the server side and store all the results in a Gridview ...

Can someone explain why my table in Laravel is only showing the third set of data and not the others?

I'm facing an issue with displaying all of the data in my table named taglineImageCarousel. The problem lies in the slide_ID column, where it is being populated with data from slide-01, slide-02, and slide-03. Below is the code snippet: taglineImage ...

Leveraging Vue.js to showcase API information through attribute binding

My application is designed to allow a user to select a Person, and then Vue makes an API call for that user's posts. Each post has its own set of comments sourced from here. You can view the codepen here Here is my HTML structure: <script src="h ...

Consolidate your jQuery functions to avoid repetition

In my form, I have multiple select inputs organized by theme. Each group has a master select option that allows users to set all selects within the group to the same value (gradescales is a method that provides grades 1-8). How can I streamline this proce ...

Sorting files in jquery file upload

Has anyone had experience using the jQuery-File-Upload library from https://github.com/blueimp/jQuery-File-Upload? I'm currently facing an issue and wondering if anyone could assist me in sorting the files in a different manner. By default, this scrip ...

What is the best way to target an anchor element that includes a particular word using jquery or css?

I attempted $('a[title="*"]').find('contains("PDF")').css({'background-color':'red'}); Unfortunately, this code is not working as expected. To clarify, I am searching for a specific word in the title. ...

Switching the way hyperlinks behave when clicked, from requiring a double-click to a single

My code is working properly, but I need my links to open with just a single click. The issue is that the delete, approve, and not approve links require a double click for their function to run. I'm hoping someone can help me with this. index.php < ...