When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows:

$(window).scroll(function () {    
  if ($(window).scrollTop() > 175) {
$('#location_menu').css('position', 'fixed').css('top','0px').css('z-index','1000');
$('.first').css('padding-top','415');}
  else { 
$('#location_menu').css('position', 'relative').css('z-index','1');
 }});

However, the problem I am facing is that the scroll is not smooth, and when the element changes from position:relative to position:fixed, there is a noticeable jump of about 415px. This jump is equal to the height of the submenu.

Below is the CSS code for reference:

 <div id="location_menu" >submenu content
 </div>

 <div id="content" class="location_detail first">content beneath submenu
 </div>

I tried adding a line for .first to set a padding-top of 415px when the page is scrolling and reaches within 175px of the top of the page .css('padding-top','415'). However, this adjustment does not seem to be working correctly. There is no visible change, so it seems like I may have implemented it incorrectly.

Should I explore using a different scrolling function instead of the one listed above?





After some trial and error, I have modified the code based on the suggestion from @Danko. Here is the updated code:

$(window).scroll(function () {
  var $conten = $('.first'),
      $menu = $('#location_menu')
      scrollpos = $(window).scrollTop();
  if (scrollpos >= 175) {
      $conten.css('padding-top','365px');
      $menu.css('position', 'fixed').css('top','0px').css('z-index','1000');
  } else {
      $conten.css('padding-top','0');
      $menu.css('position', 'fixed').css('position', 'relative').css('z-index','1');
  }
});

Answer №1

Update

After fully grasping the question, I created a demo at this link: http://codepen.io/anon/pen/BdkLf.

The main function looks like this:

$(window).scroll(function () {
  var $menu = $('#location_menu'),
      $content = $('#content'),
      scrollPos = $(window).scrollTop();
  if (scrollPos >= 175) {
      $menu.css( {
        "top" : "0",
        "position": "fixed"
      });
      $content.css('top','375px' );
  } else {
      $menu.css( {
        "position": "relative",
        "top" : "175px"
      });
      $content.css('top','175px');
  }
});

Here, the value of 175 represents the initial distance from the top, while 375 is the sum of the distance and the height of your menu.

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

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

An error handling event for XHTML compliance, similar to the HTML onerror event, is designed to address the issue of

Below is a piece of code that handles hiding the placeholder (imagecontent) for dynamically populated empty images and their captions: <head> <script type="text/javascript"> function hideEmptyImage() { document.getElementById(&q ...

"PHP MySQL news error" - An unexpected error occurred

Just incorporated a news system using MySQL/PHP, it functions flawlessly; however, encounters errors when inserting HTML. For instance, inserting a YouTube video results in the addition of / or \ Can someone advise on what changes need to be made in ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

Uploading files asynchronously with Erlang Cowboy using AJAX

I am facing an issue with AJAX file uploading to Erlang Cowboy. I am able to stream the file upload with mutltpart/form-data. <form method="post" enctype="multipart/form-data"> However, I am unable to stream the file uploading using AJAX because it ...

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

What about a Material UI-inspired homepage design?

Looking at the demo image on the main page for Material UI has me really impressed. I am interested in using a similar theme with MUI for my web application. Can you advise me on how I can achieve this look, or do I have to start from scratch? https://i.s ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

Trouble with basic JavaScript functionality in a React component

Here is a unique component code snippet: import React, {Component} from 'react'; import 'D:/School/Alta/interactiveweb/src/webapp/src/App.css' class Chat extends Component { test() { alert(); } render() { return <nav ...

Modifying property values using the onError event when encountering an error with the MUI DateTimePicker and

My goal is to set the 'myError' variable to true when MUI DateTimePicker throws an onError event, but for some reason it's not working. The code itself seems correct because if I replace () => {setValue({ ...value, ...

What are some techniques for locating an element in Selenium when it has no tags?

I'm facing a challenge in my code where I need to ensure that the message "Product successfully added to your shopping cart" appears after adding an item to the cart. Here, there is no specific tag enclosing the text, making it tricky to target for ve ...

The image is not aligning properly within the navigation bar

I had some queries in mind: 1) How can I ensure that the circular profile image on the rightmost side fits within the header without overflowing? 2) How do I properly align the last three images at the bottom (in the "R" class), with adequate spacing bet ...

Changing the input value in Nuxt / Vue 2 after it has been overridden

I'm working on a feature where the user's typed keys are converted to the last single upper-cased character (for example, 'a' becomes 'A', 'abc' becomes 'C'). Here is my current code snippet: <template& ...

What sets apart the method of assigning event handlers using bind() versus each() in jQuery?

Could someone explain the difference between using bind() to assign event handlers and using each() for the same task? $(function () { $('someElement') .bind('mouseover', function (e) { $(this).css({ ...

Issues arise when trying to integrate iframes with Ionic and AngularJS, as they

Using iframes in my ionic app to display webpages within the application has presented a challenge. This is what I currently have implemented: <iframe class= 'webPage' name= "eventsPage" ng-src="{{object.url}}"></iframe> The issue ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

Can a universal Save File As button be created for all web browsers?

Currently, I am in the process of developing a music player on the client side and I am seeking a method to save playlists that include mp3 data. Concerns with localStorage The restriction of a 5mb limit for localStorage makes it impractical for my needs. ...

What methods can be used to validate an undefined value?

exploding right now if (myObject.myKey.myThing){ } undefined myThing cannot be read What approach can be taken to determine if myThing is defined before entering the if block? ...

Tips for coloring just the letters and excluding the Bengali Kar symbol

The Bengali language consists of 40 consonants, including ক, খ, গ, ঘ, ঙ, চ, ছ, জ, ঝ, ঞ, and more. Additionally, there are 10 vowels in the form of Kars, such as া, ি, ী, ু, ূ, ৃ, ে, ৈ, ো, and ৌ. My goal is to highli ...

How to get an empty object as a response in a NODE.JS request?

For some reason, I am attempting to send an object to my backend. Even though I can retrieve valuable information from my network's payload, my req.body consistently returns an empty object. View my issue ...