The webpage fails to return to its original position after the script has been executed

My website has a sticky div that stays at the top when scrolling down, but does not return to its original position when scrolling back up.

Check out this example

function fixDiv() {
var $div = $("#navwrap");
if ($(window).scrollTop() > $div.data("top")) { 
    $('#navwrap').css({'position': 'fixed', 'top': '0', 'width': '100%'}); 
}
else {
    $('#navwrap').css({'position': 'absolute'});
}
}

$("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load
$(window).scroll(fixDiv);

Answer №1

The alignment of the top is not being properly adjusted.

Check out this solution:

function fixDiv() {
  var $div = $("#navwrap");
  var top = $div.data("top");
  if ($(window).scrollTop() > top) { 
    $('#navwrap').css({'position': 'fixed', 'top': '0', 'width': '100%'}); 
  }
  else {
    $('#navwrap').css({'position': 'absolute', 'top' : top + 'px'}); //reset to absolute and reposition the top
  }
}

$("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load
$(window).scroll(fixDiv);
#container {
    padding: 100px 0 2500px;
}
#navwrap{
    position:absolute;
    width: 100%;
    height: 50px;
    background-color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
    <div id="navwrap">NAV WRAP</div>
</div>

See the updated code in this Fiddle: https://jsfiddle.net/5ADzD/755/1

Answer №2

If you find yourself in the else block, consider using either relative or static positioning to ensure your element returns to its original layout position.

For a visual example, check out this link: http://jsfiddle.net/9DKcF/321/

The reason behind this recommendation is that absolute behaves similarly to fixed, causing the element to be removed from the normal layout flow. However, the key distinction is that while fixed remains fixed in place, absolute will be positioned relative to its closest positioned parent element.

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

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Immediate display of collapsed/toggle menu in a Bootstrap navbar

I have created a bootstrap responsive navigation menu that collapses into a box when the page is resized. It's a standard menu with bootstrap, but I'm facing an issue where the menu automatically appears when the page gets small instead of needin ...

What is the best technology to implement for a band website design?

I'm in the process of creating a website for my friend's band, and I need some creative input. The site will feature minimal content such as a bio, news, and embedded audio/visual material. While my web development skills are decent, I'm loo ...

Navigating with Vue Router on Internet Information Services (IIS)

I am encountering difficulties understanding why my routes are failing when I refresh my VueJS application hosted on IIS. Everything works fine during normal browsing, but once I press F5 or update view information through a button, a 403 error is thrown. ...

The promise was made but the function was never carried out

exports.index = function(req, res) { moviedb.indexMovie().then(function(){ console.log("DATABASE VALUES READ SUCCESSFULLY"); }); }; var moviedb = module.exports = { indexMovie : function() { return new P(function(resolve, reject){ ...

The jQuery script tag fails to recognize click events once dynamically loaded with the load event

Hey there, I recently utilized this script in a SAP WebDynpro setup to dynamically load and employ jQuery. The onload event of the script tag is functioning well as I can select the text of the focused element. However, I am facing issues with registering ...

Utilizing Next.JS and Nodemailer to seamlessly send emails through a contact form

I'm facing an issue with my contact form in next.js. Everything was working fine until I deployed it on Vercel. Although I don't see any errors, I am not receiving emails on my Gmail account after submitting the form. Additionally, I am not getti ...

What's the best way to include various type dependencies in a TypeScript project?

Is there a more efficient way to add types for all dependencies in my project without having to do it manually for each one? Perhaps there is a tool or binary I can use to install all types at once based on the dependencies listed in package.json file. I ...

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Utilizing a relationship's remote method in Loopback

My current project involves using loopback where I have a MyUser model that is related (hasMany) to a SellerRequests model. After discovering that I can create a new seller request linked to the user by making a POST request to /api/MyUsers/:id/sellerRequ ...

Gallery of Disappearing Images

I am encountering issues with the image gallery on my website, as it seems to create a space to the right when viewed on screens smaller than 350px. This results in a gap on the entire right side of the page. My goal is to make this image gallery responsiv ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

Trying to select the first tab using jQuery. Unfortunately, the only method that seems to work is causing an error

Currently, I am attempting to automatically choose the initial tab using jQuery. The following method is successful: $('#tabs').tabs('option', 'selected', 0).trigger(); However, it results in a Firebug error related to the ...

Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks. My failed attempts so far: $('.chips').on('chip.delete', function(e, chip){ console.lo ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

Activate all chosen CSS circles

I'm currently working on creating a progress bar using CSS circles. The idea is that when you click on each circle in sequence (1, 2, 3), all three circles and the line connecting them will fill up with red color. If you then go back (3, 2, 1), the co ...

Navigational Scroll Parallax Issues

I have been trying to implement a basic 2 layer parallax effect using ScrollMagic on my index page. The layout consists of a large image with content below it, but I am facing some challenges. Despite going through the documentation and source code multipl ...