Toggle Class Based on Scroll Movement

I am currently designing an HTML page that includes a small navigation bar located halfway down the page. I am aiming to have this navigation bar stick to the top of the page (become fixed) once it reaches the top. Here is the code I have tried:

The script:

<script>
$(function() {
    var header = $(".clearHeader");
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 100) {
            header.removeClass('scrollHeader').addClass("fixedHeader");
        } else {
            header.removeClass("fixedHeader").addClass('scrollHeader');
        }
    });
});

</script>

The HTML:

<div class="scrollHeader">
            <div class="row" style="background:#444;">
            <div class="container">
            <a href="#"><div class="col-sm-3 smallNav">
            Perks
            </div></a>
            <a href="#"><div class="col-sm-3 smallNav">
            Growth
            </div></a>
            <a href="#"><div class="col-sm-3 smallNav">
            Technology
            </div></a>
            <a href="#"><div class="col-sm-3 smallNav">
            Apply
            </div></a>
            </div>
            </div>
            </div>

The CSS:

.scrollHeader { position: relative !important;}
.fixedHeader {position: fixed !important; }

Unfortunately, my current code is not functioning as expected. Any advice or suggestions? I am using jQuery 1.9.1. Fiddle

Answer №1

Upon initial inspection, it appears that you may not be selecting the correct element in the beginning of your code.

var header = $(".clearHeader");

However, looking at your HTML, there is no element with the class "clearHeader", so this line of code will not work. Have you considered changing it to

var header = $(".scrollHeader");

This adjustment might solve your issue.

Additionally, adding top:0px; to your fixedHeader class will ensure that the navigation bar stays fixed at the top of the page.

Check out the code in action here: http://jsfiddle.net/5d7ymoc0/2/

For an extra smooth navigation scroll effect, you can try this: http://jsfiddle.net/5d7ymoc0/4/

Answer №2

Should $('.clearHeader') actually be $('.scrollHeader') ?

If so...

$(function() {

    navPos = $(".scrollHeader").position().top;

    $(window).scroll(function() {    
        if(navPos>0 && $(window).scrollTop()>navPos) {              
            $(".navbar").addClass("navbar-fixed-top");
        } else {
            $(".navbar").removeClass("navbar-fixed-top");
        }

        if (scroll >= ) {
            header.removeClass('scrollHeader').addClass("fixedHeader");
        } else {
            header.removeClass("fixedHeader").addClass('scrollHeader');
        }
    });
});

Answer №3

If you're looking to keep the header at the top while scrolling, this code can help you achieve that.

Take a look at this example on jsfiddle: http://jsfiddle.net/5d7ymoc0/3/

Implementation in JavaScript:

$(function() {
    $(window).scroll(function() {
        $(".smallNav").css({"position":"fixed","top":"0px"});
    });
});

Implementation in CSS:

.scrollHeader { position: relative !important; }
.fixedHeader { position: fixed !important; }
.smallNav { background: #333; color: #fff !important; padding: 10px; font-size: 20px; text-align: center; }
.wrapper { height: 2000px; }

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

Utilizing the power of Scoped CSS with Bootstrap/Bootstrap-Vue Integration

I'm currently working on a chrome extension and utilizing Bootstrap-Vue in my Vue files. I have imported bootstrap/bootstrap-vue into my js file, but the styling is being applied globally. Is there a way to scope the Bootstrap only onto specific inser ...

Struggling to integrate a functional update button into my Material UI datagrid version 5.6.1

I'm facing a challenge in adding a button to the rows of my Material UI DataGrid component. Here is my DataGrid component setup: <DataGrid rows={adminStorage} columns={columns} autoPageSize getRowId={(logistics) => logistics._id ...

(Javascript - Arrays) Find the leftmost and rightmost connected characters

Looking for the leftmost and topmost connected '1' character in a 2D matrix? Find the most left & top connected '1' character Find the most right & bottom connected '1' character EDIT 2.0: To start, provide the coordina ...

Choose a specific <div> element by its unique ID and trigger a click event on it as soon as the page loads

There is a div element on my webpage tagged with the ID of #activateeditbutton. I am hoping to have this specific div trigger a click event upon the page's initial loading. In an attempt to achieve this functionality via jQuery, I have written the fo ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

Mongoose is unable to update arrays, so it will simply create a new array

Having trouble updating my collection without any errors. Can someone lend a hand? I've been at this for 3 hours now. const product_id = req.body.cartItems.product_id; const item = cart.cartItems.find(c => c.product_id == product_id); i ...

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

What is the best way to apply overlays to customize a specific part of a single character while also accommodating dynamic width adjustments?

Query Is it feasible to style a specific portion of a single character? Interpretation You cannot apply CSS attributes to parts of characters. However, if you wish to style only a particular section of a character, there is currently no standardized met ...

AngularJS $injector.unpr Error: Understanding and Resolving Common Dependency Injection

As a beginner in AngularJS JavaScript, I have recently started learning and practicing with some small sample programs. However, when attempting this particular code snippet, I encountered an error that I need help resolving. <body ng-app="myApp"> ...

Guide on positioning two background images next to each other on a page?

Looking to replicate a design using CSS that requires editable background images via a CMS. The left image needs an angled/slanted right edge with a gold border, while the right image should be parallel. Content placement is not a concern at this stage. V ...

Validate user credentials using both jQuery and PHP to display an error message if login details are incorrect

Working on a form validation using jQuery and PHP. I am utilizing an .ajax request to the server in order to verify if data has been entered into the form, and execute different actions based on the callback response received from the server. For instance, ...

Attempting to retrieve AJAX response in JavaScript by utilizing an OOP object

Here is the code snippet I am working with: function CreateDiv(D) { D.body = function () { var d = $.ajax({ type: "GET", url: "Default.aspx", data: 'Ext ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

What is the proper method for securing this?

Trying to retrieve 'this' within a method that is invoked by pressing a button, where this points to both the class and the pressed button: p.myVar = 'apple'; $('.go').on('click', this._init); p._init = function(e ...

When a npm package consists of multiple files, what is the best way to import them?

I have an npm package that consists of three files in the dist folder, generated by webpack: https://i.sstatic.net/td5Us.png Within the package.json file, I have designated the sample.js file as the main one: "main": "dist/sample.js", ...

Tips for displaying javascript code containing variables in the executeScript method

I'm currently working on a selenium script that involves executing JavaScript code using the executeScript method. I've run into an issue when it comes to handling single (') and double quotes (") while passing variables. Not Working: js.e ...

My Ajax request in Javascript is encountering failure in Chrome due to AdBlock. What alternatives can I consider in this situation

Attempting to execute an ajax function $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { However, when running it on Chrome in a live environment, it fails due to adblock. I rely on javascript/jquery as my primary tools. Any ...

Ways to navigate private property using the App Component in Angular 4

I have successfully implemented code in my app component to retrieve the current URL and display it in app.component.html. app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Compone ...

Encountering a problem where updating the selected option in a dropdown does not properly refresh the HTML

I am currently working with a dropdown menu containing countries. Initially, the selected item is set to Ukraine. <select id="country" name="country"> <option value="US">USA</option> <option value="UG">Uganda</option> ...