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

Ensure that you include validation in the ajax request when loading the message content from a separate file

ajax code for adding data to the database <script type="text/javascript"> $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var dataString = 'content='+ textcontent; if(textcontent=='') ...

A CSS selector that can target a neighboring element with the identical class

How can I use a CSS selector to highlight the last adjacent elements with the same class? In the example code below, the first three and last two elements share the same class. However, I am looking to specifically highlight Two, Threee and Six, Seven. & ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Exploring JavaScript Unit Testing: Essential dependencies for testing with Karma, jasmine, and bootstrap

After creating an application using AngularJS and additional tools based on bootstrap, I am now facing the challenge of testing everything. However, there seems to be a problem with Karma and Jasmine as an exception is thrown when running the tests. The i ...

What is the best way to access a JSON Array in php without using any specified keys?

I'm dealing with a JSON object created in JavaScript and passed to PHP via AJAX. The issue I'm facing is that I can't figure out how to assign keys to each JSON object within the JSON array. Here's an example of how the JSON array looks ...

it will still function properly regardless of the width being set to zero

Is anyone able to explain the strange phenomenon I am experiencing with this code snippet? In this particular example, I have set the width of selector h3 to 0. However, when viewing it in IE 9 using F12 development tools, I can see that the width is indee ...

The issue of the window.open method malfunctioning on Internet Explorer 9

Struggling to make it work in IE9: Note: I forgot to mention that $variable is coming from a $_GET request based on a drop down menu selection. I am currently offline, <a href="#" onclick="window.open('https://domain.com/contact-form?chatq=& ...

Creating dynamic and fluid motion with Bezier curves on canvas

I am currently working on creating a line that spans across the canvas from left to right. In these early stages of development, I am using a step-by-step animation approach with the following function: timer = window.setInterval(draw_line, 30); Here is ...

Limitations on Embedding Videos with YouTube Data API

I have been using the Youtube Data API to search for videos, but I am encountering an issue with restricted content appearing in the results. Specifically, music videos from Vevo are showing up even though I only want videos that can be embedded or placed ...

Trouble triggering hidden radio button in Angular 9 when clicked

I have implemented radio buttons within a div with the following CSS styles (to enable selection by clicking on the div): .plans-list { display: flex; justify-content: center; margin: 2rem 0; .plan { display: flex; margin: 0 0.5rem; p ...

What is the TypeScript equivalent of the Java interface.class?

Can you write a Java code in TypeScript that achieves the same functionality as the code below: Class<?> meta = Object.class; and meta = Processor.class; // Processor is an interface In TypeScript, what would be the equivalent of .class? Specifica ...

Incorporating SSL into an Express web application

I have taken over a project that I want to enhance further. The project is built on Express and Peerjs, with a server and client (vue.js) application in place. One feature of the project involves a video stream. In order to test the application, I need to ...

Error: The 'length' property of the twitter object is not defined and cannot be read

I am trying to fetch data from my Twitter account using PHP and JSON. My PHP code is working fine, but I am facing an error with jQuery. Uncaught TypeError: Cannot read property 'length' of undefined $(document).ready(function() { var dm ...

Switch it up - modify the directory for static assets

I developed an application using create-react-app. Our server configuration stores all files, except for index.html, in a folder named static. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> ...

Tips for declaring a particular type during the process of destructuring in Typescript

I have my own custom types defined as shown below: export type Extensions = | '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' | '.txt' | '.jpg' | '.csv' | '. ...

When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once. HTML <!DOCTYPE ht ...

Guide to displaying WordPress functions within an accordion in my loop

Currently, I'm working on implementing a vertical accordion feature that will display blog posts within each section. The idea is to have 5 of the most recent posts displayed in the accordion, with each post showing the date (day/month/year) and title ...

Getting data from a latin1 (iso-8859-1) database using javascript/nodejs: Tips and Tricks

My ancient mysql database (mysql 5.0.2) is in latin1 format and I'm encountering an issue with getting data from it. Non-ascii characters such as Â, À, and Á are appearing as 'ef bf bd' in hex, which means different characters are being d ...

Adding animation to a div that is being appended can be done by using JavaScript functions and

I am looking to incorporate animation into my title div. Below is the HTML code I have so far: <div class="particles" id="tittle"> <!-- Displaying title from Firestore using JavaScript --> </div> Here is the CSS cod ...

Creating an atom without any boundaries: A step-by-step guide

While browsing the Atom forum, I stumbled upon a post discussing scripts for enhancing the UI of Atom. I'm curious about where to place these scripts. Should they go in the Atom init script? Any guidance would be highly valued. Visit this link for m ...