Tips for embedding Jquery code within Vuejs applications

Trying to code a Vue.js Navbar that changes color when scrolling using Jquery and CSS script. It works, but I encountered an error with Vue.js not supporting the syntax '$' after page refresh, resulting in a "$ not defined" error message. As a newcomer to Vue.js, I apologize if there are any errors in my implementation. Any assistance would be greatly appreciated. Thank you :).

Here is the Vue.js code :

.navbar{
  transition:500ms ease;
  background: transparent;
  font-weight: 600;
} 


.navbar.scrolled {
  background:#fff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
} 

.nav-link {
  color: white;
}

.nav-link:hover {
  color: lightgray;
}
.nav-link:focus {
  color: lightgray;
}

.navbar-brand.change-black, .nav-link.change-black {
  color:#000;
}

.nav-link.change-black:hover, .nav-link.change-black:focus {
  color:#0d6efd;
}
<template>
    <b-app>
        <b-nav class="navbar navbar-expand-lg pt-12 pb-12 fixed-top fluid"
        data-aos="fade-down" data-aos-duration="700"
        >
            <b-container>
                    <b-col lg="3">
                        <b-nav-item class="navbar-brand" href="#">
                            <span>APR</span>
                        </b-nav-item>
                    </b-col>
                    <b-col lg="8" class="d-flex"> 
                        <b-nav-item class="nav-link" href="#">Home</b-nav-item>
                        <b-nav-item class="nav-link" href="#">Procedure</b-nav-item>
                        <b-nav-item class="nav-link" href="#">About</b-nav-item>
                    </b-col>
                    <b-col lg="1" class="d-flex" right>
                        <b-nav-item-dropdown
                        id="my-nav-dropdown"
                        text="Masuk"
                        toggle-class="nav-link-custom"
                        right
                        >
                            <b-dropdown-item>Lecturer</b-dropdown-item>
                            <b-dropdown-divider></b-dropdown-divider>
                            <b-dropdown-item>Secretary</b-dropdown-item>
                        </b-nav-item-dropdown>
                    </b-col>
            </b-container>
        </b-nav> 
    </b-app>
    
</template>

<script>
export default {
        name: 'CoverLayout',
        data () {
            return {
            }
        },
}

$(window).scroll(function(){
$('.navbar').toggleClass('scrolled', $(this).scrollTop() > 50);
$('.nav-link').toggleClass('change-black', $(this).scrollTop() > 50);
$('.navbar-brand').toggleClass('change-black', $(this).scrollTop() > 50);
$('.back-to-top').toggleClass('active', $(this).scrollTop() > 50);
});

</script>

[Works fine without refreshing][Error occurs upon refreshing]

Answer №1

Avoid using jQuery with Vue and instead opt for plain vanilla JS. It's perfectly capable of handling the task, especially with the use of event listeners.

For example:

const navBar = document.querySelector(".navbar");
const navLink = document.querySelector(".nav-link");
const navBarBrand = document.querySelector(".navbar-brand");
const backToTop = document.querySelector(".back-to-top");

window.addEventListener('scroll',handleScroll);

function handleScroll(){
      let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;

  if(scrollPosition >50) {
    navbar.classList.add("scrolled");
    navLink.classList.add("change-black");
    navBarBrand.classList.add("change-black");
    backToTop.classList.add("active");
 } else {
    // ... 
 }
 
}

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

The image zoom function is malfunctioning when trying to adjust the image position

Having some trouble with a code for image zoom in/out. When I adjust the position of the image by applying margin left to either the image or the image container (#view), it affects the zoom functionality - causing the image to move to the left during zoom ...

Tips for delaying my response in nodejs until the loop is complete

This is the code I'm currently working with: myinsts.forEach(function (myinstId) { Organization.getOrgById(myinstId,function (err, insts) { res.json(insts); }) }); I am using Node.js and encountering an error message that says "Can't set hea ...

Tips for utilizing console log within a react form component

I'm currently exploring ways to communicate with a React form in order to provide it with an object.id for updating purposes. While I can successfully console log the object.id within the update button and modal, I am struggling to confirm if the val ...

The segmented button's dropdown menu in Bootstrap is malfunctioning on Firefox version 27.0.1

I'm attempting to create a basic search bar using Bootstrap's segmented button feature (check out an example at http://getbootstrap.com/components/#input-groups-buttons-segmented). This is the code I have so far, and it's accessible on jsfi ...

Discover the method for obtaining a selected element in a bootstrap dropdown that is dynamically populated

Similar to the question asked on Stack Overflow about how to display the selected item in a Bootstrap button dropdown title, the difference here is that the dropdown list is populated through an ajax response. The issue arises when trying to handle click ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

The landscape orientation media query does not adhere to the specified maximum width

I am currently working on creating a mobile landscape design for a website specifically tailored for iPhone SE and iPhone 12. In the process, I encountered an issue that caught my attention: Within two different breakpoints, I made adjustments to the top ...

angular2 : problem encountered with communication to rest api

Transitioning from PHP to Angular2 has been quite challenging for me, especially when trying to use a real rest API like "Tour of Heroes". I initially thought it would be simple... Currently, I have set up a functional API with Express: curl -XGET http:/ ...

What is the best way to display all checked checkboxes even when the page is reloaded?

I am facing an issue with my website - it is using JavaScript to search for checked checkboxes. $(function () { var $allELements = $('.input-box'); var $selectedElementsListing = $('#selectedElements'); var $selec ...

Filtering images by their class using a drop-down menu allows for easier organization and sorting based

While browsing around, I came across another inquiry regarding filtering images by category using input form and jQuery. It was similar to what I am trying to achieve. I experimented with some JSFiddles but unfortunately had no luck. If you're curiou ...

Toggle class on element based on presence of class on another element

If I have 4 boxes and the user is required to choose one. I aim to assign an active class to the box that the user clicks on. However, if the user selects another box, I want to remove the class from the first clicked box and apply it to the newly clicked ...

Laravel - Jetstream with InertiaJS: Implementing guards in the main header menu of AppLayout.vue

Is there a way to utilize guards for adding a specific admin menu entry using guards? I am aware that passing guard-"data" from controllers to view is possible as mentioned in the documentation: class UsersController extends Controller { public functio ...

nextJS does not recognize the term 'Window'

I'm encountering the error "window is not defined" in my NextJS project. The variable isMobile determines whether the window size is less than 767.98 to handle the hamburger menu functionality. This code worked in ReactJS but seems to be causing issue ...

Universal compatibility for web displays

I've been conducting testing on a website across Chrome, Firefox, and Internet Explorer, utilizing the CSS code snippet below: #foot_links1, #foot_links2, #foot_links3 { position: absolute; margin-top: 55px; margin-top: 14em; color: # ...

Innovatively blending captivating visuals with informative text, our presentation seamlessly

I'm struggling to resolve a basic code issue and thought you might be able to assist me. Please have a look at the provided sample code on this page: <http://jsfiddle.net/UniqueUser/kkaYc/> As you can observe, when selecting images from the me ...

Enhancing security through route encryption in Vue.js without relying on webpack

Is it possible to encrypt the route html/js in Vue or vue-router and then decrypt and use it at the other end? export default{ template:'', data:... methods:.. } The goal is to minimize code exposure for security purposes, without using w ...

What is the most effective method for retrieving client-side generated controls and data in ASP.net?

I have successfully created a table of form fields using ASP.net and the repeater control, populated with data from a database. Now, I have enabled users to add new rows by using jQuery to dynamically add rows to the client-side HTML table (which is rende ...

Cheerio doesn't exit the loop prematurely

The Cheerio/JQuery documentation mentions that using return false in a loop should terminate it early. Below is the code snippet in question: "use strict"; let cheerio = require('cheerio'); let $ = cheerio.load('<a href="www.test.com"&g ...

Struggling to find multiline content in a SWIFT message using regex

Looking into a SWIFT message using RegEx, here is an excerpt: :16R:FIN :35B:ISIN CH0117044708 ANTEILE -DT USD- SWISSCANTO (CH) INDEX EQUITY FUND USA :16R:FIA The goal is to extract information in group 3: ISIN CH0117044708 ANTEILE -DT USD- SWISSCANTO (C ...

What sort of JavaScript WYSIWYG text editor provides formula support?

Looking for a Javascript rich text editor that offers formula selection in the toolbar. Any recommendations? ...