Vertical stability bar

I need help creating a vertically fixed navigation bar for my website. Currently, I am using a method that has been discussed in various posts:

HTML:

<html>
<head>
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{% static 'navbar.css' %}">   

    <script type="application/javascript">
        $(document).ready(function () {
            var navPos = $('.nav_menu').offset().top; //Sticky navbar
            $(window).scroll(function () {
                var scrollPos = $(this).scrollTop();
                if (scrollPos >= navPos) {
                    $('.nav_menu').addClass('fixed');
                } else {
                    $('.nav_menu').removeClass('fixed');
                }
            });
        });
    </script>
    .....
    <div class="nav-container">
        <div class="nav_menu">
            Bars go here
    ....

CSS:

.nav-container .nav_menu.fixed {position: fixed; z-index: 10000; top: 0; width: 195px; padding-left: 8px}

The current solution works well, with the navbar sticking to the top left side of the page and following the scroll perfectly. However, I want the bar to only follow vertically and stay in place if someone scrolls horizontally. How can I achieve this?

Answer №1

To prevent horizontal scrolling, you can offset the left scroll:

var $window = $(window);
var navPos = $('.nav_menu').offset().top; //Sticky navbar

$window.scroll(function() {
  var scrollPos = $window.scrollTop();
  var left = 0 - $window.scrollLeft();

  if (scrollPos >= navPos) {
    $('.nav_menu').addClass('fixed').css('left', left + 'px');
  } else {
    $('.nav_menu').removeClass('fixed').css('left', 0);
  }
});
body,
html {
  height: 1000px;
  width: 2000px;
  position: relative;
  margin: 0;
  padding: 0;
}

.nav_menu {
  height: 50px;
  background-color: blue;
  width: 195px;
}

.fixed {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br><br><br>
<div class="nav_menu"></div>

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

coming back to the cordova application after using the browser

I recently developed a basic app using the ionic framework. There is a feature in the app that opens an external payment gateway in a system browser to process payments. After successful payment, a script on my server sends an HTML page to display a succes ...

The row count feature is ineffective in Materialize CSS when adjusting the text area

Can the row count of a text area in materialize css be initialized with a specific number using "rows='20'"? How can we adjust the default row count? Here is an example of code that attempts to set the row count but doesn't work: <div c ...

Discovering a sophisticated way to locate a span element using the not(p) selector in Selenium

Within a span element with an ID, there is a mixture of text and a paragraph tag. The goal is to use selenium webdriver to pinpoint the street address in the mix below: <span id="myspan"> <p>fullname</p> street address - has no ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

How to show a tooltip inline by utilizing CSS styling

Working on a sticky side bar menu with a tooltip feature. While it appears correctly in Chrome and Safari, the tooltip is off-center in IE. This snippet seems to be causing the issue: /* Vertically center tooltip content for left/right tooltips */ .tool ...

Setting up a textarea tooltip using highlighter.js

I'm experimenting with using highlighter.js within a textarea. I've customized their sample by substituting the p with a textarea enclosed in a pre tag (for right-to-left language settings). <div class="article" style="width: 80%; height: 80% ...

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

Understanding MUI5 prop handling

Recently, I decided to experiment with Material UI 5 sx props just for fun. I encountered a bit of confusion while trying to replicate the behavior of the previous MUI 4 makeStyles function. Specifically, I was attempting to pass JSS classnames to sx props ...

How do I retype an interface from a dependency?

It's difficult to put into words, so I have created a repository for reference: https://github.com/galenyuan/how-to-retyping My goal is to achieve the following: import Vue from 'vue' declare module 'vuex/types/vue' { interfac ...

Combining color and typography classes using Tailwind merge is currently not supported

In my custom styling setup, I have created a custom color class called text-green (colors) and a custom typography class called text-card-highlight (utilities), which includes font size and weight attributes. However, when using tailwind-merge, only one of ...

Transforming an image into a CSS-powered website menu button: Step-by-step guide

I am currently using images as button backgrounds, and I have programmed them to change when the button is clicked to give the impression that it is being pressed. However, I am looking to enhance the responsiveness of the page, so that the images also cha ...

Identify the difference between a regular function and a constructor in JavaScript

How can we determine whether a function in javascript is a simple, plain (anonymous) function, or a constructor (a function with a prototype)? I have developed the following function for this purpose: function checkFunctionType(value) { var ownPropert ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

Is it possible to modify variables in the controller when the route is changed?

My application utilizes a template and several views that are dynamically rendered based on their route: popApp.controller('HomeCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

Tips for importing a different js file from an npm package without needing to include the entire node_modules path

When using the ES2016 import syntax to load the select2 library from an npm module via Webpack, everything works smoothly and the select2.js file is loaded from the node_modules directory. The node_modules directory also contains a full version of the lib ...

submitting image data from HTML5 canvas using an HTML post request

I am having issues sending canvas data to the server side as an image. Despite making an HTTP post request, I am unable to retrieve the data on the server side. $_POST remains empty, even though I can see the image data when console logging the object on t ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

CSS: Struggling to Keep Footer at the Bottom of the Page

I've been struggling to get my footer to stick to the bottom of the page, but I just can't seem to make it work. I've searched online for solutions with no success, so I thought I would ask for help here. http://jsfiddle.net/f54eq3w8/ Here ...

Issue with Navigation Scrolling Feature on Wordpress

I am in the process of implementing a 'scroll-nav' for my website. To achieve this, I decided to separate the Navigation into two sections and incorporate some jQuery: <nav class="main-nav clearfix"> <?php wp_nav_menu(array('th ...