Adding a class in JavaScript as an element scrolls

I am trying to implement a script that adds the class navbar-fixed-top to the navigation when the user scrolls. Here is the code I have so far:

var nav;
function yScroll(){
    nav = document.getElementById('nav');
    yPos = window.pageYOffset;
    if(yPos > 150){
        nav.className = nav.className + " navbar-fixed-top";
    } else {
        nav.className = nav.className - " navbar-fixed-top";
    }
}
window.addEventListener("scroll", yScroll);

However, I am encountering an issue where the script keeps adding the navbar-fixed-top class every time yPos is greater than 150. This results in multiple instances of the same class being added as I scroll up and down.

Is there a way to ensure that the class is only added once, or do you have any alternative solutions? I have two navigations and I only want both of them to be fixed after the user has scrolled, hiding the top one from view.

Answer №1

If you are utilizing jQuery, consider the following code:

nav.addClass("navbar-fixed-top")

and

nav.removeClass("navbar-fixed-top") 

This might be the solution you are looking for:

var nav;
function yScroll(){
    nav = $('#nav');
    yPos = window.pageYOffset;
    nav.removeClass("navbar-fixed-top");
    if(yPos > 150){
        nav.addClass("navbar-fixed-top");
    }
}
window.addEventListener("scroll", yScroll);

Answer №2

Make sure to verify if the class already exists in this way....

var nav;
function yScroll(){
    nav = document.getElementById('nav');
    yPos = window.pageYOffset;
    var hasClass = nav.className.indexOf("navbar-fixed-top");
    if(yPos > 150 && hasClass == -1){
        nav.className = nav.className + " navbar-fixed-top";
    } else if (yPos < 150 && hasClass != -1) {
        nav.className = nav.className - " navbar-fixed-top";
    }
}
window.addEventListener("scroll", yScroll);

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

Navigating through pages in an Angular application can be easily achieved using Angular Routing

I've been struggling to get this feature to work correctly. Despite trying different configurations outlined in various sources such as this, that and the other, I keep encountering a 404 error whenever I try to refresh the page. Oddly enough, enterin ...

Creating intricate HTML components using jQuery/Javascript

My current challenge involves receiving data from JSON and dynamically displaying it on a web page within complex HTML structures, such as tables with lists. Every time new JSON data is received, I need my HTML elements to be dynamically regenerated. For ...

Leverage ESlint for optimal code quality in your expressjs

Is there a way to use ESlint with Express while maintaining the no-unused-vars rule? After enabling ESlint, I am encountering the following issue: https://i.stack.imgur.com/7841z.png I am interested in disabling the no-unused-vars rule exclusively for e ...

Navigating through a HTML email Listserv with a click event scrolling feature

I am looking to create an interactive HTML email with a link that can scroll the recipient's browser to a specific section within the email. I am considering using Javascript and jQuery for this functionality. Can someone guide me on how to implement ...

Access-Control-Allow-Origin does not accept null as the origin with XMLHttpRequest

Similar Question: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin XMLHttpRequest cannot load file://… Origin null is not allowed by Access-Control-Allow-Origin My goal is to access my JSON file using the following ...

Generating identical circles using PointsMaterial and CircleGeometry

My goal is to generate circles using two different methods: By utilizing a circle sprite and drawing it with Points and PointsMaterial Using basic circle buffer geometries Unfortunately, I am facing challenges trying to align them due to the size discrep ...

Switching from using ngRouter to ui-router is a common

After purchasing an angularjs template for my application, I noticed that ngRouter was used instead of ui-router, which I am more comfortable with. So, I decided to switch to ui-router and update all the routes. However, I encountered some extra code in my ...

Unable to choose more than one radio button using Angular.js

Currently, I am facing an issue with selecting multiple radio buttons using Angular.js. Below is the code snippet that demonstrates my problem. <div class="input-group bmargindiv1 col-md-12"> <label class="checkbox-inline"> <input ...

HTML - one div's child element takes precedence over another div

My HTML page features two consecutive divs. The first div contains a child span that has a relative position, causing it to overlap the second div. I have implemented click events for both divs. However, when I click on the span that overlaps the second d ...

Instead of using `await asyncCall()`, try using `(await asyncCall())[0]`

After examining the Typescript code below, I'm curious to understand the rationale behind assigning myArray with (await asyncRPCCall())[0] instead of simply using await asyncRPCCall(). Why is the result placed inside () and why return only the first e ...

Installing the error package resulted in the following error: "Error: module 'nopt' not found."

After attempting to install node modules, I encountered the error message "Error: cannot find module 'nopt'." I tested various solutions, but none of them seemed to work. The image below shows the attached error message. { "name": "server", ...

What is the best way to determine if an item qualifies as an Angular $q promise?

In my project, I have an existing API library that is not Angular-based. This library contains a method called .request which returns promises using jQuery.Deferred. To integrate this with Angular, I created a simple service that wraps the .request method ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

Calculate the sum of all values within a list and showcase the total price using React JS

I'm currently working on creating a bill and I need to be able to add items to the bill multiple times while also incrementing the total price accordingly. The total amount should be displayed, and when decreasing the quantity of an item, the price sh ...

Checking if a number includes the present year

Facing an issue with one of my form fields where the Roll number should be in the format YY-XXX YY - representing the last two digits of the current year XXX - a three-digit number I am looking for ways to validate these types of numbers using jQuery. A ...

Loading identical code in two different div elements

I am in the process of designing a comprehensive resource database featuring a side-scrolling container. Once a user clicks on a thumbnail within the container, the contents of a corresponding div will fade in and display specific category content. Each di ...

How to utilize PHP to create a multiple select form for filtering results in a MySQL

I have been attempting to create a query using the results from a search form. In my form, I have a field called "state". My goal is to allow users to select multiple states and receive a list of results that include all the selected states. Currently, I o ...

Ways to retrieve the marginLeft of an element set with absolute positioning?

Currently, I am attempting to display an information box when hovering over an element with the mouse. The issue I am facing is that the element moves, and I need to determine its left margin. However, the element does not have a margin-left property in ...

What steps are involved in incorporating dynamic pagination in PHP using this particular snippet of code?

I am looking for a way to display a list of numbers from 1 to 1000 in a single line with the ability to scroll. However, I need to exclude both "Prev" and "1" from this list. How can I achieve this? Below is the code snippet that I currently have: echo ...

Flask web framework fails to deliver Jquery ajax json get call

I've been attempting to make a simple jQuery AJAX call to fetch JSON data, but I'm running into issues and struggling to understand why. Below is the code. It appears correct to me. $(document).ready(function() { function onDataReceived (d ...