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

Exception encountered for Internet Explorer when attempting to launch from WebDriver: 405 Method Not Allowed

After trying to launch IE from Webdriver and clicking on save, I encountered a "405 Method not allowed" exception. However, when I manually launched IE and clicked on save, it worked fine. I'm perplexed by this issue. Any ideas as to why it might be ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

WP Ajax failing to work in the else statement

I am currently developing a WordPress plugin that includes a special feature. This feature involves a checkbox that, when checked by a user, saves a specific value in the database using ajax. Conversely, when the checkbox is unchecked, the value should be ...

Difficulty with animated presentations

As a developer with limited CSS experience, I am trying to create a CSS3 slideshow using only two images. After discovering some interesting code for this purpose, which can be found here, I decided to make a small change to the original code (specifically ...

"Divs of the same type automatically adjust size to fit within the

I am currently exploring the possibility of creating a versatile component that can be customized based on the needs of its parent element, whether through bootstrap or traditional flexbox / CSS grid. I want to determine the level of reusability this compo ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

Tips for updating the selected date format in a Material Table component using React

In the context of using a material table in React, the columns set up are as follows: columns={[ { title: 'Name', field: 'name', type: 'string', }, ...

What is the best way to incorporate data from my Input field into my Vue.JS application's existing data structure

Struggling with integrating new users into my personal project, particularly in passing input values (userName and userAge) to the parent element for addition to playersData. Here is a sample code snippet from the child component: `<template> <d ...

An unanticipated issue has occurred: TypeError - the product information being searched for is not defined

import { useContext, useEffect, useState } from "react" import Layout from "../components/Layout" import { ProductsContext } from "../components/ProductsContext" export default function CheckoutPage(){ const {selecte ...

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

Using jQuery and AJAX to dynamically add data to POST parameters

Hello, I have a question that may sound like one from a newbie. I am trying to figure out how to insert a variable into a parameter for a POST request instead of simply writing the number in directly: var x = 3; id=(the var x needs to be here)&appid=4 ...

What could be causing the client to not receive the socket.io broadcast in the designated rooms?

My client isn't receiving the broadcast sent to the room. I have tried replacing socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser); and it works, but I prefer using rooms in this scenario. Any ass ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

Challenges with Hover Dropdowns in Bootstrap Navigation Menu

Check out this screenshot of a navbar PSD design I'm aiming for: To make my navbar dropdown show up upon hovering, I've implemented the following JavaScript: $('.navbar .dropdown').hover(function() { $(this).find('.dropdown-men ...

Effective approach for managing a series of lengthy API requests

I am developing a user interface for uploading a list of users including their email and name into my database. After the upload process is complete, each user will also receive an email notification. The backend API responsible for this task is created u ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

Incorporating a Favicon into your NextJs App routing system

Encountering an issue with the new Next.js App Router. The head.js files have been removed, thus according to the documentation I need to implement metadata in layout.ts. My favicon file is named favicon.png. How should I specify it within the following c ...