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

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Struggling to access a PHP variable in a JavaScript file through AJAX

After studying numerous examples on how to pass a PHP variable to a JavaScript file, I have yet to successfully accomplish it. This is my PHP file: $title = $json["title"]; echo json_encode($title); And here is my app.js JavaScript file: $.ajax({ ...

Error Encountered in Laravel 5.2 FormBuilder.php

Encountering Laravel 5.2 ErrorException in FormBuilder.php on line 1235 stating that the method 'style' does not exist. This error has me perplexed. I have already made updates to my composer.json file by adding "laravelcollective/html": "^5.2" ...

Converting JSON information into a mailto hyperlink

Can anyone help me figure out how to encode a mailto link properly with JSON data in the query parameters, ensuring that it works even if the JSON data contains spaces? Let's consider this basic example: var data = { "Test": "Property with spaces" ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

The issue with style.background not functioning in Internet Explorer is causing complications

I am currently developing a JavaScript game that involves flipping cards. However, I have encountered an issue with the style.background property. It seems to be functioning correctly in Chrome but not in Internet Explorer. Here is the problematic code sn ...

The function is defined, but it cannot be set to null

Having trouble understanding this error message "Cannot set properties of null." I'm attempting to update the innerHTML with the output text from four functions that my button triggers. However, it seems to be stopping at the first function now even t ...

What is the best way to utilize the handlebars-helpers library within an express.js application?

Currently I am using hbs as my template engine in express.js. The handlebars-helpers library from assemble is something that I find extremely useful. However, I am unsure about how to integrate this library into my project. I have also been unable to loca ...

Tips for safeguarding the security of my PHP API when accessed through Ajax using OAuth2

I've developed a cross-origin ajax application that utilizes some personal APIs I created. Now, I'm looking to enhance the security measures so only my application has access to the API. After researching, I came across OAuth2 at OAuth2. I foll ...

The issue of multiple columns not displaying correctly when set to a height of 100

I am struggling with a seemingly simple task. I want to create two columns on my page, each with a width of 50% and a height of 100% so they completely fill the screen side by side. However, no matter what I try, they do not align properly and end up float ...

Getting the selected value from a dropdown menu in ReactJS

I am working on creating a form that resembles the following structure: var BasicTaskForm = React.createClass({ getInitialState: function() { return { taskName: '', description: '', emp ...

Utilizing Array.from with a XPathResult: A Comprehensive Guide

In my sample document, I found 138 nodes with the tag td using querySelectorAll. Array.from(document.querySelectorAll('td')).length 138 However, when I tried to do the same using XPath, I did not get any result: Array.from(document.evaluate(". ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

Tips for transferring information to an input field's value

There's an input box with an empty value that needs to be filled with data. <input type="text" value="" class="box"> $('.skills-tags').on('click', function(){ var value = $(".skills-tags").val(); $('.label-pr ...

Pass a value from PHP to $.get function

Looking to enhance the user experience on my website, I am currently in the process of updating my form submission method from form action to ajax. The code is functioning correctly and the server side is able to update the database. However, I am facing a ...

Sending multiple HTTP requests sequentially

I've been attempting to send a request object to a server repeatedly in a loop, aiming to execute the task 1000 times. The scenario is reminiscent of the movie Office Space, where a small sum is extracted from numerous bank accounts. Here's the ...

Error: Uncaught TypeError - The function indexOf is not defined for e.target.className at the mouseup event in HTMLDocument (translator.js:433) within the angular

Upon clicking on an SVG to edit my data in a modal bootstrap, I encountered the following error: Uncaught TypeError: e.target.className.indexOf is not a function at HTMLDocument.mouseup (translator.js:433) This is my SVG code: <svg data-dismiss ...

Setting default values for JSON objects by analyzing the data of other objects within the array

I've been grappling with this issue for about 6 days now, so please bear with me if my explanation is a bit convoluted. I'm using NVD3 to showcase graphs based on data retrieved from BigQuery. While the data and graph setup are correct, the probl ...

How to make Angular 5 wait for promises to finish executing in a for loop

My task involves working with an array like this: arr = ['res1', 'res2', 'res3']; For each value in the arr, I need to make an API call that returns a promise. arr.forEach(val => this.getPromise(val)); The getPromise me ...