Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll.

I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll.

If anyone has any advice or can point me in the right direction, I would appreciate it!

CodePen link: http://codepen.io/anon/pen/OpjZEL

$(window).scroll(function() {
  if ($(document).scrollTop() > 500) {
    $('.content').removeClass('fixed');
  }
});
.container {
  margin-top: 100px;
  height: 1000px;
}

.content {
  position: relative;
}

.fixed {
  position: fixed;
  top: 10%;
  width: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="content fixed">
    <h1>content</h1>
    <p>Donec ut arcu quis enim vehicula aliquam vel a ligula. Nulla sagittis eros eu molestie mattis. In at arcu nisi. Nam feugiat posuere mi eget iaculis. Aliquam volutpat lectus pretium dictum venenatis. Nulla congue maximus mauris in porttitor. Nullam
      non enim eget ante malesuada pharetra. Curabitur semper dui quam, vitae eleifend lectus tempus sit amet. </p>
  </div>

</div>

Answer №1

There's an issue when you remove the class .fixed because it not only eliminates the position: fixed declaration, but it also removes the top and width declarations. To fix this, make sure to reapply these properties to the .content class after removing it. Keep in mind that without the .fixed class, the element defaults to position: relative, meaning that top will no longer function as expected. Instead, use margin-top as an alternative:

$(window).scroll(function() {
  if ($(document).scrollTop() > 500) {
    $('.content').removeClass('fixed');
    $('.content').css('margin-top', '550px'); // Adjust for additional scroll
    $('.content').css('width', '30%');
  }
});
.container {
  margin-top: 100px;
  height: 1000px;
}

.content {
  position: relative;
}

.fixed {
  position: fixed;
  top: 10%;
  width: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="content fixed">
    <h1>content</h1>
    <p>Donec ut arcu quis enim vehicula aliquam vel a ligula. Nulla sagittis eros eu molestie mattis. In at arcu nisi. Nam feugiat posuere mi eget iaculis. Aliquam volutpat lectus pretium dictum venenatis. Nulla congue maximus mauris in porttitor. Nullam
      non enim eget ante malesuada pharetra. Curabitur semper dui quam, vitae eleifend lectus tempus sit amet. </p>
  </div>

</div>

I've also prepared a new CodePen demonstration, which can be viewed here.

I hope this explanation proves helpful! :)

UPDATE:

To return the element to its original state upon scrolling back up, include an else statement to reverse the changes made by the initial if condition:

else if ($(document).scrollTop() <= 500) {
  $('.content').addClass('fixed');
  $('.content').css('margin-top', '0');
}

Below is a functional example:

$(window).scroll(function() {
  if ($(document).scrollTop() > 500) {
    $('.content').removeClass('fixed');
    $('.content').css('margin-top', '550px');
    $('.content').css('width', '30%');
  } else if ($(document).scrollTop() <= 500) {
    $('.content').addClass('fixed');
    $('.content').css('margin-top', '0');
  }
});
.container {
  margin-top: 100px;
  height: 1000px;
}

.content {
  position: relative;
}

.fixed {
  position: fixed;
  top: 10%;
  width: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="content fixed">
    <h1>content</h1>
    <p>Donec ut arcu quis enim vehicula aliquam vel a ligula. Nulla sagittis eros eu molestie mattis. In at arcu nisi. Nam feugiat posuere mi eget iaculis. Aliquam volutpat lectus pretium dictum venenatis. Nulla congue maximus mauris in porttitor. Nullam
      non enim eget ante malesuada pharetra. Curabitur semper dui quam, vitae eleifend lectus tempus sit amet. </p>
  </div>

</div>

I've updated the pen with these changes, available here.

Please note that adjusting the margin-top value of 550px may be necessary for a smoother transition :)

I trust this information proves beneficial! :)

Answer №2

Your codepen performs perfectly as it is. The reason for the disappearing effect is due to the lack of substantial content within the paragraph. I tested with additional text in the paragraph, and the code functioned without any issues.

Take a look at it yourself http://codepen.io/anon/pen/KWveaX

The snippet showcases the toggleClass functionality

$(window).scroll(function() {
  if ($(document).scrollTop() > 500) {
    $('.content').toggleClass('fixed');
  }
});
.container {
  margin-top: 100px;
  height: 1000px;
}

.content {
  position: relative;
  top:0px!important;
}

.fixed {
  position: fixed;
  top: 10%;
  width: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="content fixed">
    <h1>content</h1>
    <p>Donec ut arcu quis enim vehicula aliquam vel a ligula. Nulla sagittis eros eu molestie mattis. In at arcu nisi. Nam feugiat posuere mi eget iaculis. Aliquam volutpat lectus pretium dictum venenatis. Nulla congue maximus..."
      (truncated here for brevity)
      

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

Position validation in jQuery is crucial for ensuring that form

After attempting to implement the jquery validate plugin by following the example provided at http://docs.jquery.com/Plugins/Validation, I have encountered some challenges in my own code. The issue lies in determining where to call the validation function. ...

Which is more efficient: Editing the image 'src' or replacing the 'img' tag within a Div?

var currentImage = 0; var totalImages = 8; $(document).ready(function(){ $("#next-img").click(function(){ currentImage = currentImage + 1; if (currentImage > totalImages) {currentImage = 1;}; $(".img-class").attr('src',"http://examp ...

The active class in the navbar is malfunctioning in Bootstrap 4

I've been searching high and low to figure out how to add an active class to the current open link in my navbar. I've scoured Google and Stack Overflow for answers, but everything I found only applies to hash-type navbars using href="#". None of ...

The alignment of the table appears off on Internet Explorer, while it is perfectly centered on all other web

I'm encountering a strange issue with my table alignment on Internet Explorer. The table is offset to the right in IE, but perfectly centered in other browsers like Edge, Firefox, and mobile browsers. I am using Bootstrap for my design, but haven&apos ...

Bootstrap modal fails to appear on the screen

I am in need of assistance. I have a bootstrap template with a footer, and I am trying to integrate a modal. However, when I click the modal button, the modal does not appear. Is there a missing plugin that needs to be added to my template? <script sr ...

Excluding certain source files in Typescript's tsconfig is a common practice to

My attempt to configure Typescript to exclude specific files during compilation is not working as expected. Despite setting exclusions in my tsconfig.json file, the code from one of the excluded files (subClassA.ts) is still being included in the compiled ...

Utilizing Axios to pass multiple values through a parameter as a comma-separated list

Desired query string format: http://fqdn/page?categoryID=1&categoryID=2 Axios get request function: requestCategories () { return axios.get(globalConfig.CATS_URL, { params: { ...(this.category ? { categoryId: this.category } : {}) } ...

Configuring Next-auth CredentialProvider and setting up redirection

I'm feeling a bit lost when it comes to understanding how the credentials provider and redirects work. The documentation mentions that the credentials provider doesn't support a callback and is specifically for OAuth providers, which I understand ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

jQuery function designed for elements inside modal dialog not triggering

After implementing a jQuery UI modal dialog, everything seems to be working correctly. However, I have noticed a problem with some elements within the dialog. For example: <div id="test_div"> Test Click me </div> Although the elements app ...

display active users in the chatroom sidebar

Currently, I am working on developing a chatroom application but have encountered an issue with displaying online and offline users. I have implemented a session for tracking online users - when a user logs in, the session is updated in the database to ind ...

Enlarging an image on canvas and creating a repeating pattern

My canvas size is 500px x 500px. I have a png image that matches the canvas size, which you can view here. I am looking to resize the image to 100px x 100px and then use it as part of a repeat pattern on the canvas. This is how I achieve this: // First d ...

Alert: A notification appears when executing Karma on grunt stating that 'The API interface has been updated'

While executing karma from a grunt task, I encountered the following warning: Running "karma:unit" (karma) task Warning: The api interface has changed. Please use server = new Server(config, [done]) server.start() instead. Use --force to continue. A ...

Avoiding the insertion of styles into the HEAD section when using Webpack MiniCssExtractPlugin in combination with Create React

Currently, I am utilizing create-react-app to develop a component library with Storybook JS. The ultimate goal is to release an NPM package containing these components for use in various projects. Within this library, SASS is employed, complete with global ...

Customizing CSS Styles in ASP.NET MVC for Multilingual Websites

We are looking to make our ASP-MVC website multicilingual and support different languages. One challenge I am facing is how to apply distinct style-sheets for each language, especially when dealing with right-to-left (RTL) languages like Hebrew or Arabic c ...

Issues with Vue enter transitions not functioning as expected

I am currently involved in a project where I need to implement enter and exit animations for some components. When a component enters the screen, it should come from the bottom, and when it leaves, it should go upwards. The intended functionality is that w ...

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

Is there a way to remove specific mesh elements from a scene in Unity?

When I create multiple mesh objects with the same name, I encounter difficulties in selecting and removing them all from the scene. Despite attempting to traverse the function, I have not been successful in addressing the issue. event.preventDefault(); ...

Conceal the scrollbar when the expansion panel is in its collapsed state

One issue I am encountering is that the scroll-bar appears when the expansion panel is collapsed, but not when it's expanded. Here are the references: Collapsed Expanded <mat-expansion-panel class="panel"> <mat-expansion-panel-he ...

Table of Wordpress posts

There has been a question on how to easily add tables to blog posts without having to use HTML. While some are comfortable inserting the code directly into the blog, others like my friend prefer alternatives that don't involve coding. Is there a simpl ...