Troubleshooting a position: fixed conflict in CSS or browser caused by a jQuery script

Check out this CodePen example. Go to the tab block by scrolling down. When you scroll to the top, it adds the 'sticked' class, and when it reaches the bottom of the parent element, it gets the 'sticked2' class. The problem arises when you set top: 1px or more with the 'sticked' class, causing a bug (?) that stops the script from working correctly. Why does this happen?

var $window = $(window);

$window.scroll(function() {
  var labels = $('.forlabels'),
    labelsSec = $('.forlabels-section'),
    bottomOfLabels = labels.outerHeight() + labels.offset().top,
    bottomOfLabelsSec = labelsSec.outerHeight() + labelsSec.offset().top,
    topOfLabels = labels.offset().top,
    topOfLabelsSec = labelsSec.offset().top,
    isAboveTopSec = $window.scrollTop() < topOfLabelsSec,
    isAboveTop = $window.scrollTop() < topOfLabels,
    isBelowTop = $window.scrollTop() >= topOfLabels,
    isBelowBottom = bottomOfLabelsSec <= bottomOfLabels;


  if (!isAboveTopSec && ((isBelowTop && !isBelowBottom) || isAboveTop)) {

    $('.forlabels')
      .addClass('sticked')
      .removeClass("sticked2")
      .text("Sticked");
  } else if (isBelowBottom) {

    $('.forlabels')
      .addClass('sticked2')
      .removeClass('sticked')
      .text("Scrolled Below Bottom");
  } else {

    $('.forlabels')
      .removeClass('sticked sticked2')
      .text("Not sticked ");
  }


});
* {
  box-sizing: border-box;
}
.one-half {
  position: relative;
  padding: 0 10px;
}
.one-half {
  -webkit-box-flex: 1;
  -ms-flex: 1 45%;
  flex: 1 45%;
  -webkit-flex: 1 45%;
  min-width: 300px;
  border: 1px solid red;
  height: 100%;
}
.fbox {
  height: 1800px;
  margin-top: 100px;
  border: 1px solid #000;
  display: flex;
  align-items: flex-start;
}
.forlabels-section {
  height: 500px;
  background: green;
  position: relative;
}
.forlabels {
  height: 100px;
  background: #777;
}
.forlabels,
.forlabels-section {
  width: 200px;
}
.sticked {
  position: fixed;
  top: 0;
  bottom: inherit;
}
.sticked2 {
  bottom: 0px;
  position: absolute;
  top: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fbox">

  <div class="forlabels-section">
    <div class="forlabels">Untouched Column</div>
  </div>

  <div class="one-half columned">
  </div>

</div>

Answer №1

The main issue arises when the top property is added to the element, necessitating a recalculation of the value of $(window).scrollTop(). This recalculated value is crucial for accurate comparison with other calculated variables.

CSS :

.sticked{
  position: fixed;
  top: 1px;
  bottom: inherit;
}

JS :

var $window = $(window);

$window.scroll(function() {

  var windowScrollTop = $window.scrollTop(); // storing the value of $window.scrollTop() in a variable.
  if($('.forlabels').hasClass('sticked')) // checking if the element has the 'sticked' class which adds a 1px top margin
       windowScrollTop++; // adding 1 to $window.scrollTop() if true
  else if($('.forlabels').hasClass('sticked2'))
       windowScrollTop--;

  var labels = $('.forlabels'),
      labelsSec = $('.forlabels-section'),
      bottomOfLabels = labels.outerHeight() + labels.offset().top,
      bottomOfLabelsSec = labelsSec.outerHeight() + labelsSec.offset().top,
      topOfLabels = labels.offset().top,
      topOfLabelsSec = labelsSec.offset().top,
      isAboveTopSec = windowScrollTop < topOfLabelsSec, // replacing references to $(window).scrollTop() with the variable
      isAboveTop = windowScrollTop < topOfLabels,
      isBelowTop = windowScrollTop >= topOfLabels,
      isBelowBottom = bottomOfLabelsSec <= bottomOfLabels;

  if ( !isAboveTopSec && ((isBelowTop && !isBelowBottom) || isAboveTop)) {

    $('.forlabels')
      .addClass('sticked')
      .removeClass("sticked2")
      .text("Sticked");
  } else if (isBelowBottom) {

    $('.forlabels')
      .addClass('sticked2')
      .removeClass('sticked')
      .text("Scrolled Below Bottom");
  } else {

    $('.forlabels')
      .removeClass('sticked sticked2')
      .text("Not sticked ");
  }

});

Simply replace the above JavaScript code with your own and it should function as intended.

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 can we tally the content in the drop area using JQuery Drag and Drop?

Currently, I am developing a Jquery project that involves allowing the user to drag a 'pill' into a 'cup', and then displaying the number of pills in the cup. However, I am encountering an issue where if the user moves a pill once it&ap ...

What is the best way to incorporate an onmouseover event so that when the mouse hovers over an image, play/stop/pause buttons are displayed

Furthermore, each button should trigger an event on click. When the pause button is clicked, the button text should toggle between pause and continue, and the action should correspond to the displayed text. This is the HTML code I currently have: Includi ...

Tips for using data-id instead of id when binding in jQuery

Good morning, The code snippet I currently have makes use of an ID: $('#signup-country').bind('change keyup', function(){ Now, I am interested in using the data-id attribute instead of a regular id (in this case #signup-country). Co ...

Bootstrap Inconsistency: Unnecessary spacing on the right side of the page

The navigation bar is overflowing the viewport on smaller devices, as observed on a personal device and in Chrome developer tools. From 575px onwards, there is increasing whitespace on the side of the screen, with content occupying only 25% at its smalles ...

I am looking to set an HTML file as the homepage for my Next.js project

Is there a way in next.js to render a normal .html file (index.html) when someone visits my root directory at "https://example.com/"? I have researched and edited my config file as shown below, /** @type {import('next').NextConfig} */ const next ...

When a child element within a flex container has a relative position, the flex direction column will be overridden and

I'm having trouble with the code snippet below. For the .container, I have set display:flex; flex-direction: column; in order to position my previous and next arrows before and after the container items. However, the flex direction does not change ...

Getting Your Content Centered Horizontally with Fixed Positioning in CSS

I would like the div to be centered horizontally with a fixed position, but it doesn't seem to work in my code. Can someone help me troubleshoot? Check out the demo here. HTML: <div id="fancybox-thumbs" class="bottom" style="width: 675px;"> ...

How can you identify the resume of a web application once you return from opening the camera?

I'm working on a web application that utilizes the camera by following steps from this solution: How to access a mobile phone's camera using a web app? However, I am trying to figure out how to implement a callback function once the user return ...

Tips for limiting access to data from various tabs when the web page first loads

div#tabCtrl div#page1 This table showcases the information for tab1 div#page2 This table showcases the information for tab2 ...

Div with Sticky Header and Scrolling Ability

I am working on a project that involves creating a scrollable div with "title" elements inside. I want the title element of each section to stick to the top of the div as I scroll, similar to how a menu sticks to the top of a webpage. An example of this ca ...

The Scrapy CSS selector is not fetching any prices from the list

Having trouble with the price CSS-selector while scraping an interactive website using Scrapy. Check out the HTML screenshot I captured: https://i.stack.imgur.com/oxULz.png Here are a few selectors that I've already experimented with: price = respon ...

Transitioning the implicit width

Using implicit width, which involves adding padding to an element containing text to give the parent container a specific but unstated width, can be quite elegant. However, it poses challenges when it comes to transitions. Is there a way to achieve a trans ...

Sidebar content alignment vertically

Struggling with aligning items in a sidebar, specifically regarding the fixed footer and the overflow of the main sidebar container. Trying to achieve a layout where the scrollable element stays within the designated space. Current setup includes: ...

What is the best way to ensure that an mp3 file plays seamlessly across all pages?

Does anyone know how to ensure an mp3 file plays continuously across all pages using webform asp.net? If you have any solutions, please let me know. jQuery('#main .jp-jplayer').each(function(index) { var i = index+1; var ...

OO Design for CSS Style Elements

I'm curious about the most effective way to implement objective-oriented CSS for quick and clean reuse of components. Scenario 1: HTML: <button class="button button-submit">Submit</button> CSS: .button { /* basic styles */ } .button ...

Sending an ajax request to submit the results of jQuery.each loop

$(".submitinfo").each(function() { // Using ID as POST name and value as POST value }); // Sending the data using ajax request $.ajax({ url: 'submit.php', traditional: true, data: { 'submit':'true', 'age&a ...

Submitting form data via AJAX to PHP for processing without triggering a page reload

Could someone please help me troubleshoot why this code snippet is not functioning as expected? <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(function () { $(& ...

What is the best way to dynamically serve model data in Node.js Express?

Let's say I have a model called articleModel that has properties for title and body. I have set up a GET route to display a list of all articles like so: app.get("/articles", function(req, res) { articleMode.find() .then(function(articles) { ...

Is it possible to adjust CSS values in a relative manner?

#bar{font-size:14px;} The font size of #bar is set to 14px. #foobar{font-size:$-2px} // Fictional code The font size of #foobar is now 12px. (calculated as 14px - 2px) Is there a way to dynamically alter the value of a selector like this? ...

Establish starting dimensions and remember the previous sizes of allocations

I successfully implemented a draggable split panel using a code library from johnwalley on GitHub called https://github.com/johnwalley/allotment. My goal is to achieve the following functionalities: Clicking on Expand or collapse the allotment B should e ...