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! :)